React组件的两种写法

使用creat-react-app的单页面应用 其中的组件有两种写法, 一种是函数组件一种是class组件

函数组件:使用一个函数来定义组件,参数为props(父级传入的参数) 返回的是一个React元素,本质上就是JavaScript函数

Class组件:

使用构造器子类继承父类的props

constructor (props) {
  super(props)
}

使用es5的函数组件方式来写


function User (props) {
  console.log(props)
  let name = '自定义的字段'
  const numbers = props.numbers
  const listItems = numbers.map((x,index) =>
    <li key={index}>{x}</li>
  )

  const outerName = props.outerName
  return (
    <div className="User">
      <ul>
        <li>{name}</li>
        <li>父级元素传输的{outerName}</li>
        {listItems}
      </ul>
    </div>
  )
}
export default User;

使用es6的class组件方式来写

import React, {Component} from 'react'

class User extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '自定义字段',
      arr:[11,21,34],
      listItems: null
    };
  }
  render () {
    return (
      <div>
        {this.state.name}
        <ul>
          {
            this.props.numbers.map(item => (
              <li key={item}>{item}</li>
            ))
          }
        </ul>
      </div>
    )
  }
}
export default User
发布了177 篇原创文章 · 获赞 875 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/github_35631540/article/details/103840221