我在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示例: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)
| 归档时间: |
|
| 查看次数: |
34089 次 |
| 最近记录: |