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

Is it possible to get the container DOM element passed to React.render before the contents are overwritten?

我有一个 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并将其存储为状态?

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

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 作为 prop 传递。 (这是一个简化的示例。我正在寻找一种可扩展到容器元素的多个子元素的解决方案。)

无法在从组件内部渲染之前获取容器内容,因此我认为您无法摆脱使用 props。但是,这并不意味着您必须将 data 作为道具传递;您可以简单地捕获 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 JSBin: https://jsbin.com/rihamu/edit?html,js,output