【问题标题】:How to open a modal from a parent component and have the close action reset the parent component so that the modal can open again如何从父组件打开模式并让关闭操作重置父组件,以便模式可以再次打开
【发布时间】:2020-09-19 15:06:32
【问题描述】:

我在这里看到过类似的问题,但我对 React 比较陌生,而且我的应用程序使用的是函数式组件,而不是我能找到的大多数示例中的类。所以我找到的答案对我来说很难适应。

这是我的问题,我有一个父组件,它通过切换状态变量来显示模式,一切正常,直到我从模式中关闭模式。在这种情况下,我必须按两次父按钮才能再次打开它,因为我必须切换到 false,然后再切换到 true。

这显然不是正确的方法,但我尝试将不同的东西传递给模态,例如 setState(),但我无法让它工作。 我正在使用 semanti-ui-react

父组件代码:

import React, { useState } from "react";
import { Button } from "semantic-ui-react";
import { ModalComponent } from "/imports/ui/ModalComponent";

export const MyDashboard = () => {
    const [openModal, setOpenModal] = useState(false);

    const handleOpenModal = () => {
        setOpenModal(!openModal);
    }

    return (
        <div>
            <Button
               onClick={ handleOpenModal }
               content="Open Modal"
               color="green"
             />
            {openModal &&
                <ModalComponent
                />
                }

        </div>
  )};

模态组件代码:

import React, {useState} from "react";
import {Modal, Button} from "semantic-ui-react";

export const ModalComponent = () => {
    const [isOpen, setIsOpen] = useState(true);

    // enable form items as this functionality becomes available
    return (
        <Modal
            onClose={() => setIsOpen(false)}
            onOpen={() => setIsOpen(true)}
            open={isOpen}
        >
            <Modal.Header>A modal is showing</Modal.Header>            
                <Modal.Actions>
                    <Button
                        content="Save"
                        color='green'
                        onClick={() => {                            
                            setIsOpen(false);
                            }
                        }
                    />
                    <Button color='black' onClick={() => setIsOpen(false)}>
                        Cancel
                    </Button>
                </Modal.Actions>
        </Modal>
    );
};

我假设我必须来回传递一些状态,但我不确定如何。

【问题讨论】:

    标签: javascript reactjs semantic-ui-react


    【解决方案1】:

    试试这个:

    父组件:

    <ModalComponent toggleModal={handleOpenModal} />
    

    模态组件:

    export const ModalComponent = ({toggleModal}) => {
        ...your codes
    
        toggleIt = () => {
            setIsOpen(false);
            toggleModal();
        }
    
        return (
            ...your codes
    
            <Button color='black' onClick={toggleIt} />
                 Cancel
            <Button>
    
            ...your codes
         );
    }
    

    【讨论】:

    • 成功了,非常感谢,这让我发疯了。
    猜你喜欢
    • 2019-01-13
    • 2019-09-30
    • 1970-01-01
    • 2021-01-30
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    相关资源
    最近更新 更多