代码之家  ›  专栏  ›  技术社区  ›  JoeTidee

如何为React动态创建DOM目标。使用样式化组件创建门户?

  •  0
  • JoeTidee  · 技术社区  · 7 年前

    我正在使用 React.createPortal 要创建要插入到目标中的组件,请调用 toast-container 。目前,定义此目标的唯一方法是硬编码 <div id="toast-container" /> 直接在我的。html文件。我正在使用 styled-components 我需要一种方法来创建 烤面包容器 动态使用样式。有没有办法做到这一点,例如:

    const ToastContainerWrapper = styled.div`
        position: absolute;
        top: 0;
        right: 0;
        width: 300px;
    `;
    
    const ToastContainer = () => <ToastContainerWrapper id="toast-container" />;
    
    1 回复  |  直到 7 年前
        1
  •  -1
  •   Gorrut    7 年前

    我没有使用过样式化组件。如果要创建

    <div id="toast-container"></div>
    

    在HTML页面中,可以使用普通dom函数动态执行此操作。应该在div标记中呈现组件之前完成此操作。

    window.addEventListener('load', () => {
       const toastContainer = document.createElement('div');
       toastContainer.id = 'toast-container';
       document.body.appendChild(toastContainer); //Here the toast-container is directly inserted in the body tag.
    
       ReactDOM.render(<RComp/>, toastContainer);
    });