![](/img/trans.png)
[英]How to render other component from children on onClick event react js?
[英]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.