【问题标题】:React Render not working from inside componentReact Render 在组件内部不起作用
【发布时间】: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);

【问题讨论】:

标签: reactjs react-component


【解决方案1】:

您需要将标题存储在状态中,而不是将其保存为实例变量。这将确保 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>                          
    )
  }

【讨论】:

  • 嗯,这似乎不起作用。我也尝试使用this.setState({ title: "No more ideas" });,但仍然没有重新渲染......
  • @Kokodoko 我用changeIdeas 示例更新答案。
  • 谢谢!在使用 React 组件时,方法似乎需要 changeIdeas = () =&gt; {} 语法,而不是常规的类方法语法。虽然,render() 方法不需要这个额外的箭头?
  • 这是一个箭头方法声明:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。它确保正确的this 绑定。作为替代方案,您可以手动绑定thisonClick={this.changeIdeas.bind(this)}
  • @Kokodoko 对于事件this 指的是window,如果你没有明确地绑定到类。发生这种情况也是因为您将处理程序传递给事件间接调用的 onClick。这与您在直接调用该方法的示例中所指的示例不同。这就是为什么需要绑定。 reactjs.org/docs/handling-events.html
猜你喜欢
  • 2017-03-12
  • 2020-05-22
  • 1970-01-01
  • 2016-10-23
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多