React-Rails:如何使用ref渲染组件?

时间:2015-07-08 16:23:22

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

目前我将组件渲染到.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为我的Counter组件指定一个ref。

1 个答案:

答案 0 :(得分: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组件。

相关问题