【问题标题】:Modal not closed模态未关闭
【发布时间】:2021-11-20 15:09:16
【问题描述】:

在 react.js 中,我希望 setShowModal 在单击 Backdrop 组件并隐藏 Backdrop 组件时为 false,但 setShowModal 不为 false,甚至不显示 console.log ('a')。

import { useState } from 'react';

import Backdrop from './Backdrop';
import Modal from './Modal';

function Todo(props) {
  const [showModal, setShowModal] = useState(false);

  function showModalHandler() {
    setShowModal(true);
  }

  function closeModalHandler() {
    setShowModal(false);
    console.log('a');
  }

  return (
    <div className='card'>
      <h2>{props.text}</h2>
      <div className='actions'>
        <button className='btn' onClick={showModalHandler}>
          Delete
        </button>
      </div>
      {showModal && <Modal />}
      {showModal && <Backdrop onClick={closeModalHandler} />}
    </div>
  );
}

export default Todo;

【问题讨论】:

  • 您需要将函数 closeModalHandler() 作为道具传递并从模态组件中调用它

标签: javascript html reactjs state use-state


【解决方案1】:

closeModalHandler 函数的绑定似乎有问题。我对您的代码进行了一些更改,它实际上正在关闭模式并在控制台中删除“a”。 将函数定义为箭头函数有助于在这些情况下提供帮助。 希望它对你有用。

import { useState } from 'react';


function Todo(props) {
  const [showModal, setShowModal] = useState(true);

  const showModalHandler = () => {
    setShowModal(true);
  }

  const closeModalHandler = () => {
    setShowModal(false);
    console.log('a');
  }

  return (
    <div className='card'>
      <h2>{props.text}</h2>
      <div className='actions'>
        <button className='btn' onClick={() => showModalHandler()}>
          Delete
        </button>
      </div>
      {showModal && <button> ShowModalIsActive</button>}
      {showModal && <button onClick={() => closeModalHandler()}>Button</button>}
    </div>
  );
}

export default Todo;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多