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

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

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

但浏览器引发了我一番惊讶:

警告:getInitialState是在Loginform(一个普通的JavaScript类)上定义的。 这只支持使用React.createClass创build的类。 你是不是要定义一个国有财产呢?

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

另一个小东西,我觉得在传统的语法React.createClass是一个对象,所以其中的function是用逗号分隔,但与extends类需要分号,我不明白这一点。

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

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

 export default class Loginform extends React.Component { constructor(props, context) { super(props, context); this.state = { name: '', password: '' }; }; } 

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, };