[英]How to use arrow functions inside React.createClass
I want to use ES6 (ES2015) as much as possible for my small project. 我想尽可能地为我的小项目使用ES6(ES2015)。 Now I want to use arrow functions with React. 现在我想使用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
will be the object passed into createClass
itself, is this correct? 据我所知, this
将是传递给createClass
本身的对象,这是正确的吗? Text
instance? 如何将其绑定到Text
实例? Thanks in advance. 提前致谢。
You can change your code with ES2015
like this 您可以像这样使用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>
};
As you said, you wanted use ES6 as much as possible. 如你所说,你想尽可能多地使用ES6。 So then instead of using createClass, you can use 'React.Component', you can find more info here . 因此,您可以使用'React.Component'代替使用createClass,您可以在此处找到更多信息。
And then to use, arrow mark you can use Babel, preset-2015. 然后使用,箭头标记你可以使用Babel,预设-2015。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.