类扩展React.Component不能在React中使用getInitialState

Bri*_*ang 77 reactjs

我在React中使用ES6语法,并编写如下组件:

export default class Loginform extends React.Component {
    getInitialState() {
        return {
          name: '',
          password: ''
        };
    };
}
Run Code Online (Sandbox Code Playgroud)

但浏览器引发了我的警告:

警告:getInitialState是在Loginform上定义的,这是一个普通的JavaScript类.这仅适用于使用React.createClass创建的类.你的意思是改为定义一个州财产吗?

我可以用传统的语法来处理它,var Loginform = React.createClass但是什么是正确的ES6语法?

另一个小东西,我认为在传统语法中React.createClass是一个对象,所以它中的函数用逗号分隔,但是对于extends它需要分号的类,我不太了解它.

max*_*max 150

ES6类方法声明之间不需要分号或逗号.

对于ES6类,getInitialState已弃用,有利于在构造函数中声明初始状态对象:

export default class Loginform extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      name: '',
      password: ''
    };
  };
}
Run Code Online (Sandbox Code Playgroud)

  • 你想把它叫到哪里?在ES6类中,`this`不会自动绑定,这可能是问题的一部分:https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html #autobinding (4认同)
  • 引用链接文章:"_ React的`createClass`功能提供的其中一个细节是它自动将你的方法绑定到组件实例.例如,这意味着在单击回调中`this`将绑定到组件.随着迁移到ES6类,我们必须自己处理这个绑定.React团队建议在构造函数中预绑定._"http://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes (2认同)

Jua*_*ine 7

ES6示例:state,defaultProps,propTypes

import React from 'react'
import ReactDom from 'react-dom';
export default class Item extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            check:false,
        };
        this.click=this.click.bind(this);
    }
    click(){
       this.setState({check:true});
    }
    render(){
        const text=this.state.check?'yes':'no';
        return(<div onClick={this.click}>{this.props.name} : <b>{text}</b></div>)
    }

}

Item.defaultProps={
    comment:"default comment",
};
Item.propTypes={
    name:React.PropTypes.string.isRequired,
};
Run Code Online (Sandbox Code Playgroud)