react中Element和Component有什么区别?

React Element 是描述屏幕上所见内容的数据结构,是对于 UI 的对象表述。典型的 React Element 就是利用 JSX 构建的声明式代码片然后被转化为createElement的调用组合。而 React Component 则是可以接收参数输入并且返回某个 React Element 的函数或者类

// 当节点的type属性为字符串时,它代表是普通的节点
const Child1 = React.createElement(
  "b",
  {
    className: "child1"
  },
  "child1"
);
const Child2 = React.createElement(
  "span",
  {
    className: "child2"
  },
  "child2"
);
const Parent = React.createElement(
  "div",
  {
    id: "testButton"
  },
  Child1,
  Child2
);
ReactDOM.render(
        root,
        document.getElementById('content')
);
==>>
<div id="testButton">
  <b class="child1">
    child1
  </b>
  <span class="child2">
    child2
  </span>
</div>
==>>
// React Elements 
{ 
  type: 'div', 
  props: { 
    id: 'testButton', 
  } 
  children:[
    {
      type: 'b', 
      props: { 
        className: 'child1' 
      },
      children: "child1" 
    },{
      type: 'b',
      props: {
        className: 'child2' 
      },
      children: "child2"
    }
  ]
}


// 当节点的type属性为一个函数或一个类时当节点的type属性为一个函数或一个类时为组件
// es5
function Button ({ onLogin }) {
  return React.createElement(
    'div',
    {id: 'login-btn', onClick: onLogin},
    'Login'
  )
}

// es6
class Button extends React.Component {
   render() { 
    const { children, color } = this.props; 
    return { 
      type: 'button', 
      props: { 
        className: 'button button-' + color, 
        children: { 
          type: 'b', 
          props: { 
            children: children 
          } 
        } 
      } 
    }; 
  } 
}
==>>
// Component Elements 
{ 
  type: Button, 
  props: { 
    color: 'blue', 
    children: 'OK!' 
  } 
}

results for ""

    No results matching ""