createPortal 不会覆盖 div 内容(如 ReactDOM.render)

Noi*_*art 11 reactjs

我试图ReactDOM.createPortal覆盖我也正在安装的容器的内容。然而它似乎附加了Child。

是否可以覆盖内容?如同ReactDOM.render

这是我的代码:

import React from 'react';
import { createPortal } from 'react-dom';

class PrivacyContent extends React.Component {

    render() {
        return createPortal(
            <div>
                <button onClick={this.handleClick}>
                    Click me
                </button>
            </div>,
            document.getElementById('privacy')
        )
    }

    handleClick() {
        alert('clicked');
    }

}

export default PrivacyContent;
Run Code Online (Sandbox Code Playgroud)

Rom*_*rin 5

如果您知道自己在做什么,这里有一个<Portal />组件,它在幕后创建一个门户,清空目标 DOM 节点并使用任何 props 挂载任何组件:

const Portal = ({ Component, container, ...props }) => {
  const [innerHtmlEmptied, setInnerHtmlEmptied] = React.useState(false)
  React.useEffect(() => {
    if (!innerHtmlEmptied) {
      container.innerHTML = ''
      setInnerHtmlEmptied(true)
    }
  }, [innerHtmlEmptied])
  if (!innerHtmlEmptied) return null
  return ReactDOM.createPortal(<Component {...props} />, container)
}
Run Code Online (Sandbox Code Playgroud)

用法:

<Portal Component={MyComponent} container={document.body} {...otherProps} />
Run Code Online (Sandbox Code Playgroud)

这清空了内容document.body,然后MyComponent向下传递otherProps

希望有帮助。


Shu*_*tri 3

在组件的构造函数中,您实际上可以在渲染 Portal 内容之前清除 div 的内容:

class PrivacyContent extends React.Component {

    constructor(props) {
        super(props);
        const myNode = document.getElementById("privacy");
        while (myNode.firstChild) {
            myNode.removeChild(myNode.firstChild);
        }
    }
    render() {
        return createPortal(
            <div>
                <button onClick={this.handleClick}>
                    Click me
                </button>
            </div>,
            document.getElementById('privacy')
        )
    }

    handleClick() {
        alert('clicked');
    }

}

export default PrivacyContent;
Run Code Online (Sandbox Code Playgroud)