gpt4 book ai didi

javascript - 如何在 React.createClass 中使用箭头函数

转载 作者:数据小太阳 更新时间:2023-10-29 06:10:34 28 4
gpt4 key购买 nike

我想在我的小项目中尽可能使用 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')
);
  1. 我需要做什么才能使它正常工作?
  2. 据我了解,this 将是传递给 createClass 本身的对象,是否正确?
  3. 如何将它绑定(bind)到 Text 实例?

提前致谢。

最佳答案

你可以像这样用 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>
};

Example

React - Reusable Components

关于javascript - 如何在 React.createClass 中使用箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36080354/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com