【问题标题】:React-Rails: How to render a component with a ref?React-Rails:如何使用 ref 渲染组件?
【发布时间】:2015-07-08 16:23:22
【问题描述】:

目前我在 .erb 文件中渲染我的组件,如下所示:

<%= react_component('Counter', number: @counter) %>

这个组件有一个使用promised-xhr的函数:

push: function(operation) {

    if(operation) {
      new_number = this.state.number +1;
    } else {
      new_number = this.state.number -1;
    }

 // This call works.
 // this.setState({number: new_number})

     XHR.post("/update", {
      data: {
        count: new_number
      }
    }).then(function(response) {
   // XHR.post is successful, so I can log the response.
      console.log(response.body.number);
   // But setState does not work because of 'this'
      this.setState({number: reponse.body.number})
    })

}

this.setState({number: response.body.number)} 不起作用,因为 this 不再是组件。我打算使用React.findDOMNode(this.refs.myComponent) 来查找我的组件并触发新状态。

但是,我不知道如何使用 react_component 将 ref 分配给我的 Counter 组件。

【问题讨论】:

  • 你试过.bind(this)吗?

标签: javascript ruby-on-rails reactjs react-rails


【解决方案1】:

记忆this,然后在回调中使用局部变量怎么样?

push: function(operation) {
  // ... 
  // Store `this` as local variable `_this`:
  var _this = this 

  XHR.post("/update", {/*...*/})
    .then(function(response) {
    // use local variable `_this`, which still refers to the component:
      _this.setState({number: reponse.body.number
    })
}

附带说明,ref 可能无济于事。调用getDOMNode 后,您将拥有一个 DOM 节点(内置浏览器),而不是 React 组件。

【讨论】:

  • 你是对的。 Promise 不适合我正在尝试做的事情,旧式回调也不行。我想知道如何实现一个在从请求中接收数据后改变状态的组件。
  • 在请求处理程序中使用setState 函数,如上所示。将组件分配给_this(一个局部变量),以便可以从请求处理程序中引用它。
猜你喜欢
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 2016-03-23
  • 2018-01-07
  • 2016-03-06
相关资源
最近更新 更多