React创建组件的三种方式

React 创建组件的三种方法:
1. 无状态函数式
  纯展示,不涉及state的操作,只能根据传入的props来展示,只带有render() 方法;
特点:
    组件不会被实例化,整体渲染性能得到提升
    组件不能访问this
    不能使用生命周期

2. React.createClass  
    是es5的一种方式 

3. React.Component 
    现在最常用的一种方式(es6)


后两种创建组件方式的区别:

一、函数this自绑定

React.createClass创建的组件,其每一个成员函数的this都有React自动绑定;


React.Component 创建的组件,其成员函数不会自动绑定this,需要手动绑定,否则this不能获取当前组件实例对象

 三种绑定方法:
1.构造函数 
    constructor(props){
      super(props);
      this.handleClick = this.handleClick.bind(this);
    }

2.bind(this)
   <div onClick={this.handleClick.bind(this)}></div> 3.箭头函数 
    <div onClick={()=>this.handleClick()}></div> 

二、组件属性propTypes 和默认的props属性defaultProps配置不同
class TodoItem extends React.Component {
    static propTypes = {//类的静态属性
        name: React.PropTypes.string
    };

    static defaultProps = {//类的静态属性
        name: ''
    };

    ...
}


const TodoItem = React.createClass({
    propTypes: { // as an object
        name: React.PropTypes.string
    },
    getDefaultProps(){   // return a object
        return {
            name: ''    
        }
    }
    render(){
        return <div></div>
    }
})
 
  
 
 

猜你喜欢

转载自www.cnblogs.com/jiangyuanyuan/p/11578698.html