【问题标题】:Is it possible to get the container DOM element passed to React.render before the contents are overwritten?是否可以在内容被覆盖之前将容器 DOM 元素传递给 React.render?
【发布时间】:2015-09-17 03:27:25
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    没有办法在从组件内部渲染之前获取容器内容,所以我认为你无法摆脱使用道具。但是,这并不意味着您必须将 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 JSBinhttps://jsbin.com/rihamu/edit?html,js,output

    【讨论】:

    • 谢谢。这似乎是一种合理的方法。
    猜你喜欢
    • 2014-11-29
    • 2021-11-18
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 2010-11-05
    相关资源
    最近更新 更多