关于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
);
}
}发布于 2020-12-05 04:30:25
我认为这一切都是关于后代组件的。
在上面的示例中,在所有后代都已挂载之后,将调用componentDidMount,并且只有在此之后,所有后代才会被附加到dom。
但是你可以在后代中有一些逻辑,这需要他们在dom中。
例如,你可以让子组件使用ref来计算自己在文档中的位置,这只能在ref附加到real dom时才能实现。
第二个例子,您的子输入可以在componentDidMount中进行自动聚焦。这也会生效,只有组件已经在真实的dom中了。
在这些情况下,您需要防止子级渲染,直到将this.el附加到dom为止。
https://stackoverflow.com/questions/65149344
复制相似问题