是否有可能在内容被覆盖之前将容器DOM元素传递给React.render?

时间:2015-09-17 03:27:25

标签: javascript reactjs

我有一个DOM元素container,我希望在其中使用React渲染。

<div id="container">
  <input id="ae06f4ec-5ce9-11e5-9f3f-0021cc62b713" class="child"/>
</div>

container元素已经有一些孩子需要保留属性:我需要保留子输入的id。

当我调用React.render(myReactElement, document.getElementById('container'))时,我是否可以在渲染覆盖内容之前从我的组件中获取container DOM元素,这样我就可以获取id并将其存储为状态?

我尝试在getDOMNode中的组件上调用componentWillMount,但我得到了

Invariant Violation: findComponentRoot(..., .0): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID ``.

我试图避免将输入的id作为道具传递。 (这是一个简化的例子。我正在寻找一种可以扩展到容器元素的多个子元素的解决方案。)

1 个答案:

答案 0 :(得分:1)

在从组件内部渲染之前,没有办法获取容器内容,所以我认为你不能放弃使用道具。但是,这并不意味着您必须将数据作为道具传递;您可以简单地捕获DOM节点并将它们作为道具传递,让组件完成工作。例如:

function render(elem, container) {
  // Pass the container's children (as DOM nodes) to the top-level component
  var cloned = React.cloneElement(elem, {originalChildren: container.children})
  React.render(cloned, container);
}

var Application = React.createClass({
  getInitialState() {
    // Convert the NodeList to an Array.
    var originalChildren = Array.prototype.slice.call(this.props.originalChildren);
    var ids = originalChildren.map(node => {
      return node.getAttribute("id");
    });

    return {
      ids: ids
    };
  },

  render() {
    return (
      <div>
        The IDs are: {this.state.ids.map(id => <div>{id}</div>)}
      </div>
    );
  }
});

// Now we call `render` with the same parameters we would have
// used for `React.render`; no need to do anything special.
render(<Application />, document.getElementById("container"));

以下是此代码working in a JSBinhttps://jsbin.com/rihamu/edit?html,js,output