首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将React门户直接附加到DOM节点和将React门户附加到分离的节点之间的区别?

问将React门户直接附加到DOM节点和将React门户附加到分离的节点之间的区别?
EN

Stack Overflow用户
提问于 2020-12-05 03:08:01
回答 1查看 390关注 0票数 2

关于React门户,创建一个分离的节点然后将其附加到文档与直接将门户呈现到文档中有什么区别?

在文档(https://reactjs.org/docs/portals.html)中,下面是一个示例。在挂载时,会将动态创建的DOM节点(this.el)附加到门户div。但是,直接将其附加到文档中的modalRoot元素有什么区别呢?我不太理解代码的注释部分。

代码语言:javascript
复制
const modalRoot = document.getElementById('modal-root');

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.el = document.createElement('div');
  }

  componentDidMount() {
    // The portal element is inserted in the DOM tree after
    // the Modal's children are mounted, meaning that children
    // will be mounted on a detached DOM node. If a child
    // component requires to be attached to the DOM tree
    // immediately when mounted, for example to measure a
    // DOM node, or uses 'autoFocus' in a descendant, add
    // state to Modal and only render the children when Modal
    // is inserted in the DOM tree.
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }

  render() {
    return ReactDOM.createPortal(
      this.props.children,
      this.el
    );
  }
}
EN

回答 1

Stack Overflow用户

发布于 2020-12-05 04:30:25

我认为这一切都是关于后代组件的。

在上面的示例中,在所有后代都已挂载之后,将调用componentDidMount,并且只有在此之后,所有后代才会被附加到dom。

但是你可以在后代中有一些逻辑,这需要他们在dom中。

例如,你可以让子组件使用ref来计算自己在文档中的位置,这只能在ref附加到real dom时才能实现。

第二个例子,您的子输入可以在componentDidMount中进行自动聚焦。这也会生效,只有组件已经在真实的dom中了。

在这些情况下,您需要防止子级渲染,直到将this.el附加到dom为止。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65149344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档