简体   繁体   English

React JS:避免在渲染组件时执行模态

[英]React JS: Avoid the Modal to be executed when the component is rendered

What I've noticed when using Modals in React is when the component is rendered, the body of the Modal is executed even if the visible state is false . 我在React中使用Modals时注意到的是呈现组件时,即使可见状态为false,也会执行Modal的主体。

Example: 例:

render() {
        return (
            <Modal
                title="Basic Modal"
                visible={false}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
            >
                <p>Some contents...</p>
                {console.log('visible is false but content is being executed!')}
            </Modal>
        );
    }

I want to execute the entire Modal only if the visible prop is true . 我只想在可见道具为true时执行整个Modal。 Is there a way to do it? 有办法吗?

I'm using this basic Modal Component: https://ant.design/components/modal/ 我正在使用此基本的模态组件: https : //ant.design/components/modal/

You can use conditional rendering with the logical && Operator. 您可以将条件渲染与逻辑&&运算符一起使用。
You can read more about conditional renders in the Docs. 您可以在文档中阅读更多有关条件渲染的信息
For example: 例如:

render() {
        return (
          SomeCondition &&
            <Modal
                title="Basic Modal"
                visible={true}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
            >
                <p>Some contents...</p>
                {console.log('visible is false but content is being executed!')}
            </Modal>
        );
    }

这与Modal无关,而与渲染Modal的组件有关,为什么父组件会重新渲染,console.log将始终执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM