reactjs 为什么窗体不想关闭而从应用程序启动时就打开了

idfiyjo8  于 2023-02-22  发布在  React
关注(0)|答案(1)|浏览(162)

我有一个问题模态,形式总是可见的,我不能关闭它。这是问题的函数isOpen和handleOnClose,我在React乞讨
Header.jsx

import React, { useContext, useState } from "react";
import bemCssModules from 'bem-css-modules';

import { StoreContext } from "../../store/StoreProvider";

import { default as HeaderStyles } from './Header.module.scss';
import LoginForm from "../LoginForm/LoginForm";

const style = bemCssModules(HeaderStyles)

const Header = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);

    const { user, setUser } = useContext(StoreContext);

    const handleOnClose = () => setIsModalOpen(false);

    const handleOnClick = () => {
        if (Boolean(user)) {
            setUser(null)
        }
        else {
            setIsModalOpen(true);
        }
    }

    const setProperlyLabel = Boolean(user) ? 'Wyloguj się' : 'Zaloguj się';

    return (
        <header className={style()}>
            <div className={style('logo-wraper')}></div>
            <h1 className={style('title')}>Super kursy dla programistów</h1>
            <button onClick={handleOnClick}>{setProperlyLabel}</button>
            <LoginForm handleOnClose={handleOnClose} isModalOpen={isModalOpen} />
        </header>

    );
};
export default Header;

Modal.jsx

import React, { Children, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import bemCssModules from 'bem-css-modules';

import { default as ModalStyles } from './Modal.module.scss';

const style = bemCssModules(ModalStyles);

const Modal = ({ children, handleOnClose, isOpen, shouldBeCloseOnOutsiteClick }) => {

    const modalRef = useRef(null);
    const previousActiveElement = useRef(null);

    useEffect(() => {
        if (!modalRef.current) {
            return;
        }

        const { current: modal } = modalRef;

        if (isOpen) {
            previousActiveElement.current = document.activeElement;
            modal.showModal();
        }
        else if (previousActiveElement.current) {
            modal.close();
            previousActiveElement.current.focus();
        }
    }, [isOpen]);

    useEffect(() => {
        const { current: modal } = modalRef

        const handleCancel = event => {
            event.preventDefault();
            handleOnClose();
        };

        modal.addEventListener('cancel', handleCancel);

        return () => {
            modal.removeEventListener('cancel', handleCancel)
        }
    }, [handleOnClose]);

    const handleOutsideClick = ({ target }) => {
        const { current } = modalRef;

        if (shouldBeCloseOnOutsiteClick && target === current) {
            handleOnClose();
        }
    }
    return ReactDOM.createPortal((
        <dialog className={style()} ref={modalRef} onClick={handleOutsideClick}>
            {children}
        </dialog>
    ), document.body);
}
export default Modal;

LoginForm.jsx

import React, { useContext, useState } from "react";
import bemCssModules from 'bem-css-modules';
import Modal from '../Modal/Modal'

import { default as LoginFormStyles } from './LoginForm.module.scss';
import { StoreContext } from "../../store/StoreProvider";

const style = bemCssModules(LoginFormStyles);

const LoginForm = (handleOnClose, isModalOpen) => {

    const [login, setLogin] = useState('');
    const [password, setPassword] = useState('');
    const [validateMessage, setValidateMessage] = useState('');

    const { setUser } = useContext(StoreContext);

    const handleOnChangeLogin = ({ target: { value } }) => setLogin(value);
    const handleOnChangePassword = ({ target: { value } }) => setPassword(value);

    const handleOnCloseModal = event => {
        event.preventDefault();
        handleOnClose();
    }

    const resetStateOfInput = () => {
        setLogin('');
        setPassword('');
        setValidateMessage('');
    }

    const handleOnSubmit = async event => {
        event.preventDefault();
        const { data, status } = await request.post(
            '/users',
            { login, password }
        );

        if (status === 200) {
            setUser(data.user);
            resetStateOfInput();
            handleOnClose();
        }
        else {
            setValidateMessage(data.message);
        }
    }

    const validateMessageComponent = validateMessage.length
        ? <p className={style('validate-message')}>{validateMessage}</p> : null;
    return (
        <Modal handleOnClose={handleOnClose} isOpen={isModalOpen} shouldBeCloseOnOutsiteClick={true}>
            {validateMessageComponent}
            <form className={style()} method="post" onSubmit={handleOnSubmit}>
                <div className={style('row')}>
                    <label>
                        Login:
                        <input onChange={handleOnChangeLogin} type="text" value={login} />
                    </label>
                </div>
                <div className={style('row')}>
                    <label>
                        Hasło:
                        <input onChange={handleOnChangePassword} type="password" value={password} />
                    </label>
                </div>
                <div className={style('row')}>
                    <button type="submit">Zaloguj</button>
                    <button onClick={handleOnCloseModal} type="button">Anuluj</button>
                </div>
            </form>
        </Modal>
    );
};
export default LoginForm;

存储提供程序

import React, { createContext, useEffect, useState } from "react";

import request from "../helpers/request";

export const StoreContext = createContext(null);

const StoreProvider = ({ children }) => {
    const [courses, setCourses] = useState([]);
    const [user, setUser] = useState([null]);

    const fetchDate = async () => {
        const { data } = await request.get('/courses');

        setCourses(data.courses);
    };

    useEffect(() => {
        fetchDate();
    }, []);

    return (
        <StoreContext.Provider value={[courses, setCourses, user, setUser]}>
            {children}
        </StoreContext.Provider>
    );
};
export default StoreProvider;

应用程序

import React from "react";

import StoreProvider from "./store/StoreProvider";
import Header from './components/Header/Header'

import './App.scss'
const App = () => (
    <StoreProvider>
        <Header />
    </StoreProvider>

);

export default App;

enter image description here
嗨,我有一个问题模态,形式总是可见的,我不能关闭它。这是问题的函数是打开和handleOnClose,我在React乞讨

h7wcgrx3

h7wcgrx31#

LoginForm组件传递属性的方式如下:

<LoginForm handleOnClose={handleOnClose} isModalOpen={isModalOpen} />

但是,您正在尝试像访问常规函数 * 一样访问props:

const LoginForm = (handleOnClose, isModalOpen) => {...}

您需要对包含变量的props进行反结构化:

const LoginForm = ({ handleOnClose, isModalOpen }) => {}

另一种形象化的方法是:

const LoginForm = (props) => {
  console.log(props.handleOnClose);
  console.log(props.isModalOpen);
};

相关问题