[英]How to active modal from other component using onclick (react)
Need to active modal component on other component using onClick Function.需要使用 onClick Function 在其他组件上激活模态组件。
Using Bootsratp-react modal使用 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
The modal components got button, but i need his functionality in other component.模态组件有按钮,但我需要他在其他组件中的功能。 The modal should be opening after onclick function and if statement.
模式应该在 onclick function 和 if 语句之后打开。
Thank you!谢谢!
You can solve this by getting its state by parameter.您可以通过参数获取其 state 来解决此问题。 Instead of inserting inside that component.
而不是插入该组件内部。 That way you could reuse it in a simpler way.
这样您就可以以更简单的方式重用它。
example: https://codesandbox.io/embed/goofy-khorana-tdnmow?fontsize=14&hidenavigation=1&theme=dark示例: https://codesandbox.io/embed/goofy-khorana-tdnmow?fontsize=14&hidenavigation=1&theme=dark
ps: In the example, I left the button in the component, but ideally it would be used where it is being called. ps:在示例中,我将按钮留在组件中,但理想情况下它会在调用它的地方使用。
Add data-bs-toggle="modal" data-bs-target="#example-modal-sizes-title-sm"
attributes to the button on which if clicked, modal should activate.将
data-bs-toggle="modal" data-bs-target="#example-modal-sizes-title-sm"
属性添加到按钮,如果单击该按钮,模式应激活。
This is my html code of bootstrap Modal这是我的 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>
and this is the button which when click activates the modal这是单击时激活模态的按钮
<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.