浅谈ES6 class实现React Class

来源:互联网 发布:2017宏观经济数据 编辑:程序博客网 时间:2024/05/29 17:47

使用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"));
2 0