【问题标题】:How to open & close react-bootstrap modal?如何打开和关闭反应引导模式?
【发布时间】:2021-03-30 07:22:34
【问题描述】:

我是 react 新手,我正在使用 react-bootstrap。我有一个完美工作的反应应用程序,它有 2 个组件,并且我正在使用函数组件。这是代码。

App.js

function App() {
  const [modalShow, setModalShow] = useState(false);

  return (
    <>
      <Button variant="primary" onClick={() => setModalShow(true)}>
        Launch vertically centered modal
      </Button>

      <MyVerticallyCenteredModal
        show={modalShow}
        onHide={() => setModalShow(false)}
      />
    </>
  );
}

MyVerticallyCenteredModal.js

export default function MyVerticallyCenteredModal(props) {
    return (
        <Modal
            {...props}
            size="lg"
            aria-labelledby="contained-modal-title-vcenter"
            centered
        >
            <Modal.Header closeButton>
                <Modal.Title id="contained-modal-title-vcenter">
                    Modal heading
            </Modal.Title>
            </Modal.Header>
            <Modal.Body>
                <h4>Centered Modal</h4>
                <p>
                    Cras mattis consectetur purus sit amet fermentum. Cras justo odio,
                    dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac
                    consectetur ac, vestibulum at eros.
            </p>
            </Modal.Body>
            <Modal.Footer>
                <Button onClick={props.onHide}>Close</Button>
            </Modal.Footer>
        </Modal>
    );
}

在这个阶段,我的代码运行良好。但我需要做一些改变。我需要从 MyVerticallyCenteredModal 组件中删除 show 和 onHide 道具,并从 Modal 组件中访问道具。这就是我所做的,

App.js

<MyVerticallyCenteredModal />

MyVerticallyCenteredModal.js

<Modal
  show={modalShow}
  onHide={() => setModalShow(false)}
  size="lg"
  aria-labelledby="contained-modal-title-vcenter"
  centered
>
...
</Modal>

现在我得到一个编译错误,

'modalShow' is not defined
'setModalShow' is not defined

但是如果不将 useState 从 App.js 移动到 MyVerticallyCenteredModal.js 我该怎么做呢?

【问题讨论】:

  • 能否在Modal中声明状态。我不明白你问题的最后一行:)
  • 基本上,我不想添加新状态或删除当前的useState
  • 你也写过你不能将道具传递给 Modal 对吧?
  • 做一件事维姬。将您的代码放在 Codesandbox 上并分享然后与我链接。我一定会尽力帮助你:)
  • 其实我想在组件中使用show={}和onHide={}

标签: javascript reactjs react-hooks react-bootstrap


【解决方案1】:

onClick();应该采取一个事件来控制鼠标点击:

 onClick={(e) => {setModalShow(false)}};

onHide();

注意:您也可以使用单词“event”而不是字母“e”

【讨论】:

  • 对不起,我得到了同样的错误 'setModalShow' is not defined
【解决方案2】:

状态由父组件&lt;App/&gt;控制,启动Modalbutton在App组件中。

  <Button variant="primary" onClick={() => setModalShow(true)}>
    Launch vertically centered modal
  </Button>

因此,无法从 Modal 本身控制 Modal 行为。

但是,如果您直接在 &lt;App/&gt; 组件本身中渲染您的 Modal 而不使用父组件来渲染 Modal,则可以。然后就可以做到了。

我们需要在 modal 组件内有一个小按钮,并使用 Modal 本身的状态来控制它:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2020-07-30
    相关资源
    最近更新 更多