React的几种组件

一、函数组件

  该函数在React中是一个有效的组件,可以接收唯一带有数据的props(代表属性)对象,并返回一个React元素。函数式组件要特别注意,组件名称首字母一定要大写。这种方式也成为无状态组件。

  特点有:

  1.组件不会被实例化,整体渲染性能提升了。没有实例化,就不需要分配多余的内存。

  2.不能访问this对象,像this.ref , this.state等不能访问

  3.组件无法访问生命周期方法

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

二、React.createClass组件

  ES5的原生JavaScript来实现的React组件,与函数式组件相比,React.Componen都是创建有状态的组ss件,这些组件是要被实例化的。并且可以访问组件的生命周期方法。

var InputControlES5 = React.createClass({
    propTypes: {//定义传入props中的属性各种类型
        initialValue: React.PropTypes.string
    },
    defaultProps: { //组件默认的props对象
        initialValue: ''
    },
    // 设置 initial state
    getInitialState: function() {//组件相关的状态对象
        return {
            text: this.props.initialValue || 'placeholder'
        };
    },
    render: function() {
        return (
            <div>
                Type something
            </div>
        );
    }
});

  三、class组件

  更加简洁方便,this指向该组件,可以访问到生命周期函数。数据可通过this.setState()方法进行修改。

class Welcome extends React.Component {
 constructor(props){
  super(props)//如果要使用props,这是必须的
  }
render() {
return <h1>Hello, {this.props.name}</h1>; } }

  四、组件也可以进行组合

  对有状态组件也适用。

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

 

posted @ 2020-08-18 16:03  梦为湘子  阅读(1049)  评论(0编辑  收藏  举报