我想尽可能地为我的小项目使用ES6(ES2015)。现在我想在React中使用箭头函数。
// What I want
let Text = React.createClass({
componentDidMount: () => {
setInterval(this.updateCurrentTime, 1000);
}
}
// What I have
let Paragraph = React.createClass({
render: () => (<div className="MySuperTable"><Text name="Dodo" startDate={(new Date()).toString()} /></div>)
});
let Text = React.createClass({
getInitialState: function () {
return {
currentTime: (new Date()).toString()
}
},
componentDidMount: function () {
setInterval(this.updateCurrentTime, 1000);
},
updateCurrentTime: function () {
this.setState({
currentTime: (new Date()).toString()
});
},
render: function () {
return (
<div>
<span>Hello my name is {this.props.name}</span>
<span>And I was born on {this.props.startDate}</span>
<span>And I now it's {this.state.currentTime}</span>
</div>
);
}
});
ReactDOM.render(
<Paragraph/>,
document.getElementById('container')
);
this
将成为传递给createClass
本身的对象,这是正确的吗? Text
实例?提前致谢。
答案 0 :(得分:5)
您可以使用ES2015
这样的
class Text extends React.Component {
constructor() {
super();
this.state = { currentTime: (new Date()).toString() };
}
componentDidMount() {
setInterval(() => this.updateCurrentTime(), 1000);
}
updateCurrentTime() {
this.setState({
currentTime: (new Date()).toString()
});
}
render() {
return <div>
<span>Hello my name is { this.props.name }</span>
<span>And i was born { this.props.startDate }</span>
<span>And i now it's { this.state.currentTime }</span>
</div>
}
};
let Paragraph = () => {
return <div className="MySuperTable">
<Text name="Dodo" startDate={ (new Date()).toString() } />
</div>
};
答案 1 :(得分:1)
正如您所说,您希望尽可能多地使用ES6。因此,您可以使用'React.Component'而不是使用createClass,您可以找到更多信息here。
然后使用,箭头标记你可以使用Babel,预设-2015。