转载

React.createClass vs extends React.Component

当我们学习ReactJS的时候, 都会通过官方Tutorial看到下面的写法.

import React from 'react'; let TodoItem = React.createClass({     render(){         return <div></div>     } }) 

但是, ES6实现了class. 于是, 出现了新的写法.

import React from 'react'; class TodoItem extends React.Component{     constructor(props){         super(props)     }     render(){         return <div></div>     } } 

接下来, 就对比一下这两种写法的不同之处. 例子的顺序都是先写React.createClass, 再写extends React.Component

1. propTypes 和 getDefaultProps

import React from 'react'; let TodoItem = React.createClass({     propTypes: { // as an object         name: React.PropTypes.string     },     getDefaultProps(){   // return a object         return {             name: ''             }     }     render(){         return <div></div>     } }) 
import React form 'react'; class TodoItem extends React.Component{     static propTypes = { // as static property         name: React.PropTypes.string     };     static defaultProps = { // as static property         name: ''     };     constructor(props){         super(props)     }     render(){         return <div></div>     } } 

2. 初始状态

import React from 'react'; let TodoItem = React.createClass({     // return an object     getInitialState(){          return {             isEditing: false         }     }     render(){         return <div></div>     } }) 
import React from 'react'; class TodoItem extends React.Component{     constructor(props){         super(props);         this.state = { // define this.state in constructor             isEditing: false         }      }     render(){         return <div></div>     } } 

3. this

import React from 'react'; let TodoItem = React.createClass({     handleClick(){         console.log(this); // React Component instance     },     render(){         return <div onClick={this.handleClick}></div>     } }) 
import React from 'react'; class TodoItem extends React.Component{     constructor(props){         super(props);     }     handleClick(){         console.log(this); // null     }     handleFocus(){  // manually bind this         console.log(this); // React Component Instance     }     handleBlur: ()=>{  // use arrow function         console.log(this); // React Component Instance     }     render(){         return <input onClick={this.handleClick}                                onFocus={this.handleFocus.bind(this)}                                 onBlur={this.handleBlur}/>     } } 

4.Mixin

import React from 'react'; let MyMixin = {     doSomething(){} } let TodoItem = React.createClass({     mixins: [MyMixin], // add mixin     render(){         return <div></div>     } }) 

extends React.Component 由于ES6的原因, 不支持Mixin. 但是有一些比较好的替代方案:

原文  http://imweb.io/topic/56da7609ca5e865230c1d50e
正文到此结束
Loading...