繁体   English   中英

如何使用 onclick 从其他组件激活模式(反应)

[英]How to active modal from other component using onclick (react)

需要使用 onClick Function 在其他组件上激活模态组件。

使用 Bootsratp-react 模态

import Modal from 'react-bootstrap/Modal'
import Button from 'react-bootstrap/Button'
import { useState } from 'react';

const UserModal=()=> {
    const [smShow, setSmShow] = useState(false);
  
    return (
      <>
        <Button onClick={() => setSmShow(true)} className="me-2">Small modal</Button>
        <Modal
          size="sm"
          show={smShow}
          onHide={() => setSmShow(false)}
          aria-labelledby="example-modal-sizes-title-sm"
        >
          <Modal.Header closeButton>
            <Modal.Title id="example-modal-sizes-title-sm">
              Small Modal
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>...</Modal.Body>
        </Modal>
      </>
    );
  }

  export default UserModal

模态组件有按钮,但我需要他在其他组件中的功能。 模式应该在 onclick function 和 if 语句之后打开。

谢谢!

您可以通过参数获取其 state 来解决此问题。 而不是插入该组件内部。 这样您就可以以更简单的方式重用它。

示例: https://codesandbox.io/embed/goofy-khorana-tdnmow?fontsize=14&hidenavigation=1&theme=dark

ps:在示例中,我将按钮留在组件中,但理想情况下它会在调用它的地方使用。

data-bs-toggle="modal" data-bs-target="#example-modal-sizes-title-sm"属性添加到按钮,如果单击该按钮,模式应激活。

这是我的 html 引导模态代码

<div className="modal fade" id="navSearchModal" tabIndex="-1" aria-labelledby="navSearchModalLabel" aria-hidden="true">
    <div className="modal-dialog">
        <div className="modal-content">
            <div className="modal-body">
                <button type="button" className="ms-auto rounded-circle modal-close-btn" data-bs-dismiss="modal" aria-label="Close">
                    <i className="fa-solid fa-xmark"></i>
                </button>
                <h5 className="modal-title text-center" id="navSearchModalLabel">Search for Products</h5>
                <input className="navbar-search-input my-3 w-100 px-2 py-2 rounded-pill" type="text" placeholder="Search..." />
                <div className='search-modal-results'></div>
            </div>
        </div>
    </div>
</div>

这是单击时激活模态的按钮

<button className="navbar-search-btn" type="submit" data-bs-toggle="modal" data-bs-target="#navSearchModal">
    <i className="fa-solid fa-magnifying-glass"></i>
</button>

暂无
暂无

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

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