何时使用 open 属性与有条件地渲染 Material-UI Modal 组件?

mat*_*lev 5 javascript reactjs material-ui

当使用 Material-UI 的 Modal 组件(或使用它构建的任何组件)时,使用openprop 与有条件渲染组件相比有什么好处吗?我注意到你失去了很好的结束过渡,但是如果有很多模态框,会有任何性能优势吗?

使用道具的示例open

    const [openModal, setOpenModal] = React.useState(false);

    return (
        /* code to set openModal to true */
        <Modal open={openModal} onClose={() => setOpenModal(false)}>modal stuff here...</Modal>
    );
Run Code Online (Sandbox Code Playgroud)

使用条件渲染的示例:

    const [openModal, setOpenModal] = React.useState(false);

    return (
        /* code to set openModal to true */
        {
            openModal &&
                <Modal open onClose={() => setOpenModal(false)}>modal stuff here...</Modal>
        }
    );
Run Code Online (Sandbox Code Playgroud)

jea*_*182 0

我认为第二种方法的性能可能较差,如果您查看 Modal 组件源代码,您可以看到代码中正在进行大量初始化、useEffects 和其他一些东西,每次您有条件渲染 Modal 时,它都会再次安装在 DOM 中,而如果保持由模态本身控制打开状态,则组件将不会再次安装,至少不会初始化,并且在我看来,它会更有效。我建议您阅读源代码,但对我来说总是重新渲染一些东西并且安装它会降低效率。