我有 2 個組件,每個組件都有一個模態。我希望從另一個按鈕打開其中一個模式,到目前為止,單擊該按鈕只會關閉當前活動模式,但不會打開新模式。
//Modal 1
<div className="modal fade" id="myModal">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header d-flex justify-content-center">
<h4 className="modal-title">Supplier Name</h4>
</div>
<div className="modal-body">
<h3 className="text-center mt-2">Search Bar</h3>
<form>
<input
type="text"
className="form-control"
/>
</form>
<table className="table mt-5">
<thead>
<tr>
<th>Supplier Name</th>
<th>Choose Supplier</th>
</tr>
</thead>
<tbody>
{suppliers.map(supplier => (
<tr key={supplier.supplier_id}>
<td>{supplier.supplier_name}</td>
<td><button className="btn btn-info" onClick={()=> chooseSupplier(supplier.supplier_id)} data-dismiss="modal">Choose Supplier</button></td>
</tr>
))}
</tbody>
</table>
</div>
<div className="modal-footer">
<AddNewSupplier/>
<button type="button" className="btn btn-danger">Close</button>
</div>
</div>
</div>
</div>
特別是這里是應該鏈接到第二個模式的 [AddNewSupplier] 按鈕:
<div className="modal-footer">
<AddNewSupplier/>
<button type="button" className="btn btn-danger">Close</button>
</div>
從這個模式中,我希望能夠打開第二個
//Modal 2
<a data-dismiss="modal" data-toggle="modal" href="#myModal" className="btn btn-primary">Launch modal</a>
<div className="modal fade" id="myModal" role="dialog">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">×</button>
<h4 className="modal-title">Modal Header</h4>
</div>
<div className="modal-body">
<p>Some text in the modal.</p>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
我正在使用 React、Express、Bootstrap 4。感謝任何幫助!
uj5u.com熱心網友回復:
看看你應該如何在 React 中使用 Boostrap 模態:https ://www.pluralsight.com/guides/working-with-bootstraps-modals-react
基本上,您安裝 npm 包:npm i react-bootstrap bootstrap
然后,從包中匯入 Modal,并將其用作包裝內容的組件:
<Modal>
//your content here
</Modal>
現在模態應該由狀態管理,所以你給它一個狀態:
const [isModalOneOpen, setIsModalOneOpen] = useState(false) //modal is closed
現在您可以使用該狀態將其作為道具傳遞給模態:
<Modal show={isModalOneOpen}>
//your content here and lets add a button to open the second modal from here:
<button onClick={() => setModalTwoOpen(true)}>Modal 1 will open</button>
</Modal>
<button onClick={() => setIsModalOneOpen(true)}>Open Modal 1</button> //this button will open the first modal
現在,讓我們添加第二個 Modal,與第一個相同,但狀態不同:
const [isModalTwoOpen, setIsModalTwoOpen] = useState(false);
<Modal show={isModalTwoOpen}>
//your content here
</Modal>
現在,要從任何地方關閉模態框,您只需將要關閉的模態框的狀態設定為false,例如:
<Modal show={isModalTwoOpen}>
//your content here
<button onClick={() setIsModalTwoOpen(false)}>Close this modal</button>
</Modal>
注意:如果模態 1 在一個組件中,而模態 2 在另一個組件中,那么您需要從父組件管理兩個模態的狀態。此外,正如評論中所指出的,在 modals 上打開 modals 并不是一個很好的用戶體驗,只是為了將其作為設計中的旁注。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/440870.html
標籤:javascript 反应 表示 引导程序 4
