React Render 无法在组件内部工作
React Render not working from inside component
我正在创建一个简单的 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);
您需要将标题存储在状态上,而不是将其保存为实例变量。这将确保变量被 React 跟踪,并且组件将在更改时正确更新。
constructor() {
super()
this.state = { title: "My ideas" }
}
changeIdeas = () => {
this.setState({
title: "No more ideas for today"
});
}
render() {
return (
<div>
<h1>{this.state.title}</h1>
<button onClick={this.changeIdeas}>Change ideas</button>
</div>
)
}
我正在创建一个简单的 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);
您需要将标题存储在状态上,而不是将其保存为实例变量。这将确保变量被 React 跟踪,并且组件将在更改时正确更新。
constructor() {
super()
this.state = { title: "My ideas" }
}
changeIdeas = () => {
this.setState({
title: "No more ideas for today"
});
}
render() {
return (
<div>
<h1>{this.state.title}</h1>
<button onClick={this.changeIdeas}>Change ideas</button>
</div>
)
}