gpt4 book ai didi

reactjs - 将 React 门户直接附加到 DOM 节点与附加到分离节点之间的区别?

转载 作者:行者123 更新时间:2023-12-05 06:08:16 26 4
gpt4 key购买 nike

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

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

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
);
}
}

最佳答案

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

在上面的例子中,componentDidMount 会在所有的后代都挂载之后被调用,只有在那之后,所有的后代才会被附加到 dom。

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

例如,您可以让子组件使用 ref 来计算自身在文档中的位置,只有当 ref 附加到真实 dom 时才能这样做。

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

在这些情况下,您需要阻止 child 渲染,直到 this.el 附加到 dom

关于reactjs - 将 React 门户直接附加到 DOM 节点与附加到分离节点之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65149344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com