首页 > 解决方案 > React:向根 DOM 添加模态组件

问题描述

有没有办法决定组件的 DOM 父级?我需要能够添加一个组件,并且它必须驻留在 DOM 树中并且仍然是内部组件的子组件。

类似于以下内容:

<div className="row">
    <Comp />
</div>

虽然 DOM 树是

<div id="root">
    <div class="component">
...

用例是一个自定义模式,显示为一个覆盖。

标签: reactjs

解决方案


这是 React 门户的经典应用:它在选定的 DOM 节点(父节点)中渲染选定的组件

render() {
  // React does *not* create a new div. It renders the children into `domNode`.
  // `domNode` is any valid DOM node, regardless of its location in the DOM. ( body, a div etc etc )
  return ReactDOM.createPortal(
    this.props.children,
    domNode
  );
}


推荐阅读