浅谈ES6 class实现React Class

使用ES6 class可以以一个JavaScript类来定义React Class。 1、使用React.createClass: var Counter = React.createClass({propTypes: {initial: React.PropTypes.number },getDefaultPro...

使用ES6 class可以以一个JavaScript类来定义React Class。


1、使用React.createClass:


var Counter = React.createClass({
propTypes: {
initial: React.PropTypes.number 
},
getDefaultProps: function() { 
return {initial: 0};
},
getInitialState: function() {
return {count: this.props.initial};
},
count: function() {
this.setState({count: this.state.count + 1});
},
render() {
return (
<div onClick={this.count}>
Click times: {this.state.count}
</div>
);
}
});
ReactDOM.render(
<Counter />, 
document.getElementById("timeBox")
);



2、使用ES6 class:


class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initial};
}
count() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div onClick={this.count.bind(this)}>
Click times:{this.state.count}
</div>
);
}
}
Counter.propTypes = { 
initial: React.PropTypes.number 
};
Counter.defaultProps = { 
initial: 0 
};
ReactDOM.render(
<Counter />, 
document.getElementById("timeBox")
);

 


3、使用ES6 class与React.createClass的不同:


① React.createClass提供getInitialState 方法,而ES6 class在构造函数里设置初始的state;


② React.createClass提供getDefaultProps方法和propTypes 属性,而propTypes 和 defaultProps 在ES6 class的构造函数里被定义为属性,而不是在class body里。


③ ES6 class中不会自动绑定this到实例上,必须显示的使用.bind(this) 或使用箭头函数 =>:


正确用法1:


<div onClick={this.count.bind(this)}>

正确用法2:


<div onClick={() => this.count()}>

错误用法:

<div onClick={this.count}>

建议在构造函数中绑定事件处理器,以便对于所有实例只需绑定一次:

constructor(props) {
super(props);
this.count =this.count.bind(this);
this.state = {count: props.initial};
}

直接使用:


<div onClick={this.count}>


4、无状态函数


1) 可以用JavaScript函数来定义React类,如使用无状态函数语法:

function MyBox(props) {
return <div>Hello, {props.name}</div>;
}
ReactDOM.render(
<MyBox name="react"/>, 
document.getElementById("timeBox")
);

2) 可以使用ES6箭头函数来定义React类:


const MyBox = (props) => <div>Hello {props.name}</div>;
ReactDOM.render(
<MyBox name="react"/>, 
document.getElementById("timeBox")
);

上述两种方法用于纯函数态的组件,必须没有保持任何内部状态,没有备份实例,也没有组件生命周期方法。


大多数组件都应该是无状态函数,如果可能,这将是推荐的模式。


3) 仍然可以以设置函数属性的方式来指定 propTypes 和 defaultProps:


① 用JavaScript函数:


function MyBox(props) {
return <div>Hello, {props.name}</div>;
}
MyBox.propTypes = {   
    name: React.PropTypes.string   
};  
MyBox.defaultProps = {   
    name: "react"   
}; 
ReactDOM.render(
<MyBox name="react"/>, 
document.getElementById("timeBox")
);

② 使用ES6箭头函数:

const MyBox = (props) => <div>Hello {props.name}</div>;
MyBox.propTypes = {   
    name: React.PropTypes.string   
};  
MyBox.defaultProps = {   
    name: "react"   
}; 
ReactDOM.render(
<MyBox name="react"/>, 
document.getElementById("timeBox")
);

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
廖雪
廖雪

78 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章