React 的核心就是组件. everything in react is component. 这是因为 React 的定位就是一个 View 库, 这样你就能用搭积木的方式组合独立的、简单的组件构建更复杂的组件.

创建组件之 JSX 元素

其实组件就是有特定功能的 html 标签(也就是自定义标签)

  1. const MyComponent = <div>hi, this a jsx element</div>

创建组件之 无状态 function

  1. // 需要大写字母开头
  2. const MyComponent = () => {
  3. return (
  4. <div>this is my component by function</div>
  5. )
  6. }

创建组件之 React.Component

function 创建的组件没法接受父组件传递的参数, 这里利用 es6 中 class 的构造函数来创建有状态的组件.

  1. // 这里继承 React.Component 以获得渲染到页面的方法
  2. class MyComponent extends React.Component{
  3. // render() 就是生成虚拟 dom 操作, 等价于 return React.createElement("h1")
  4. render(){
  5. return (
  6. <div>hi, this a component extends from React.Component</div>
  7. )
  8. }
  9. }

渲染

  1. // 把组件绑定到页面 id=root 的元素上
  2. ReactDOM.render(<MyComponent />, document.getElementById("root"))