https://zh-hans.reactjs.org/docs/components-and-props.html

函数式组件

实际上就是一个函数,传入props作为参数,返回一个react组件,这种就称之为函数式组件

  1. function Welcome(props) {
  2. return <h1>Hello, {props.name}</h1>;
  3. }
  4. // 是一个字符串
  5. const element = <Welcome name="Sara" />;
  6. ReactDOM.render(
  7. element,
  8. document.getElementById('root')
  9. );

class组件

使用ES语法,通过继承React.componet来创建的类,称之为class组件

  1. class Welcome extends React.Component {
  2. render() {
  3. return <h1>Hello, {this.props.name}</h1>;
  4. }
  5. }

组合组件

组件可以在其输入中返回引用其他组件,这种一般是组合组件

  1. function Welcome(props) {
  2. return <h1>Hello, {props.name}</h1>;
  3. }
  4. function App() {
  5. return (
  6. <div>
  7. <Welcome name="Sara" />
  8. <Welcome name="Cahal" />
  9. <Welcome name="Edite" />
  10. </div>
  11. );
  12. }
  13. ReactDOM.render(
  14. <App />,
  15. document.getElementById('root')
  16. );

注意

  1. 自定义组件必须是以大写字母开头,因为React默认会解析小写字母开头的标签为html标签
  2. 不能随意修改传入的props值
  3. state和props类似,但是state是私有的,完全受控于当前组件