使用 ReactJS 引用动态组件

Refs in dynamic components with ReactJS

我遇到了一个问题,但我没有找到任何相关的文档。

这是我组件的渲染方法:

render()
{
  return (
    <div refs="myContainer">
    </div>
  );
}

此外,我还有一种方法可以从我的 Java 服务器获取数据:

getAsyncData()
{
  $.get('...URL...')
    .done(function(response) {
      var list = JSON.parse(response); // This is an objects array
      var elementsList = [];

      list.forEach(function(item) {
        elementsList.push(<div ref={item.id}>{item.name}</div>);
      });

      React.render(elementsList, React.findDOMNode(this.refs.myContainer));
    });
}

在我的 componentDidMount 方法中,我只是启动异步方法:

componentDidMount()
{
  this.getAsyncData();
}

所以我从 ReactJS 收到这个错误:

Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's render method). Try rendering this component inside of a new top-level component which will hold the ref.

所以这意味着我无法使用我的动态元素,另外认为 而不是简单的 DIV 我会有一个复杂的组件,方法在 .

我该如何处理?

谢谢!

How can I deal this?

按照预期的方式编写组件。保持数据的状态。 .render() 在状态改变时调用,更新输出。

示例:

var Component = React.createClass({
  getInitialeState() {
    return {items: []};
  },

  getAsyncData() {
    $.get(...).done(
      response => this.setState({items: JSON.parse(response)})
    );
  },

  render() {
    var list = this.state.items.map(
      item => <div key={item.id} ref={item.id}>{item.name}</div>
    );
    return <div>{list}</div>;
  }
});

这就是 React 的全部意义所在:根据数据描述输出。您不是动态添加或删除元素,而是更新状态、重新渲染并让 React 弄清楚如何协调 DOM.
但是,我不清楚为什么在这种情况下需要参考。

我推荐阅读https://facebook.github.io/react/docs/thinking-in-react.html