React的Element和React.Component

React的Element是React应用程序的最小构建块,它是用来描述我们在屏幕上看到的浏览器页面上的内容。

在React中构建 Element 有两种方式:

1、JSX的方式,JSX不是React的必用技术,但它可以用来产生一个 React “element”.

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);

2、使用React.createElement方法

方法声明:

React.createElement(
  type,    //type可以是html的tag标签,例如'div'或'span',也可以是React.Component的类,或者React fragment type
  [props
  [...children]
)

示例 :

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

上述1和2的方式是等价的。

要呈现一个React element到一个root DOM节点中,需要通过调用 ReactDOM.render()方法在页面中进行呈现,下面是一个完整的示例:

import React from 'react'
import ReactDOM from 'react-dom'

class HelloMessage extends React.Component {
  render() {
    return (
      <div>
        Hello {this.props.name}
      </div>
    );
  }
}

ReactDOM.render(
  <HelloMessage name="Taylor" />,
  document.getElementById('root')
);

在上述代码中可看到React.Component组件的render()方法实际返回的就是一个React的Element

猜你喜欢

转载自www.cnblogs.com/hzhuxin/p/9329939.html
今日推荐