【发布时间】:2020-03-10 14:46:16
【问题描述】:
我正在创建一个简单的 React 组件,它会在单击按钮时更新自己的数据。令人困惑的是,html 不会自动更新,所以我手动调用 render() 函数。但即使这样也不会更新 html。如何告诉 react 重新渲染组件?
class Ideas extends React.Component {
constructor() {
super()
this.title = "My ideas"
}
changeIdeas(){
this.title = "No more ideas for today"
// how to re-render the new title? This is not working
this.render()
// also not working
ReactDOM.render(<Ideas/>, window.root)
}
render() {
return (
<div>
<h1>{this.title}</h1>
<button onClick={this.changeIdeas}>Change ideas</button>
</div>
)
}
}
ReactDOM.render(<Ideas/>, window.root);
【问题讨论】: