【问题标题】:Don't know why Portal doesn't work in my code不知道为什么 Portal 在我的代码中不起作用
【发布时间】:2021-10-19 03:32:24
【问题描述】:

告诉我哪里错了。 提前谢谢你。

控制台错误是:错误:目标容器不是 DOM 元素。

GitHub:https://github.com/Alexander-Korniichuk/React_Practice/commit/13612103a3a73fe29242970e1648c13902bad753

src/Portals/PortalAppTwo.jsx

import React, {useRef} from "react";
import ReactDOM from "react-dom";
 
export const PortalAppTwo = () => {
    const containerLink = useRef(null);
    return (
        <>
            <div className={"block"}>
                <div className="block__place">
                    <div className="block__real-place" ref={containerLink}>
 
                    </div>
                </div>
                <div className="block__place">
                    <div className="block__face-place">
                        <Boxy link={containerLink}/>
                    </div>
                </div>
            </div>
        </>
    )
}
 
const Boxy = ({link = null}) => {
    if (link !== null) return ReactDOM.createPortal(
        <div style={{
            width: "200px",
            height: "200px",
            border: "2px solid black",
            padding: "5px",
            margin: "5px",
            backgroundColor: "peachpuff"
        }}>Boxy</div>
        , link.current)
    else {
        return null
    }
}

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    问题在于link.current,您在其中呈现门户。它必须是一个 DOM 元素,您在其中使用文本“boxy”呈现 div。

    【讨论】:

    • 所以,我按照你的建议做了(返回

      错误信息

      )。不过,我有错误。
    • 这样的错误:错误:目标容器不是 DOM 元素。
    • 我克隆了你的仓库并尝试过,得到了问题。我已经改变了答案请检查它
    • 我明白你的意思。 link.current 是指向 DOM 元素的链接。为什么它不起作用?大概有错误,因为当当前 DOM 元素尚未安装时,link.current 等于 null。我尝试将我的新 DOM 节点插入到(index.html)中的现有父 DOM 元素中并且它有效,但是我想将新的 DOM 节点插入到不存在的父 DOM 元素中,该元素将在安装后稍后存在。甚至有可能做到这一点吗?
    • link.current 是指向 dom 元素的链接,但它必须是 dom 元素本身而不是指向 dom 元素的链接,是的,link.current 也是它抛出错误的另一个原因
    猜你喜欢
    • 2020-09-19
    • 2014-01-17
    • 1970-01-01
    • 2019-05-21
    • 2021-03-11
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多