我有一個Comp組件,它所做的就是顯示六次,一個按鈕,打開一個模式。下面是它的代碼。
import "././node_modules/bootstrap/dist/css/bootstrap.min.css"/span>。
import React from "././node_modules/react"/span>。
function Comp(props) {
return [0, 1, 2, 3, 4, 5]。] map(span class="hljs-params">value =>)
<>/span>
< button type="button"/span> class="btn btn-success m- 2" data-bs-toggle="modal" data-bs-target="#exampleModal">
{`點擊按鈕${value}來打開下面的Modal`}。
{/*上一行的值作業得非常好 */}。
</button>
< div class="modal fade text-white" id="exampleModal" data-bs-backdrop="static"/span> tabindex="-1"/span> aria- labelledby="exampleModalLabel"/span> aria-hidden="true"/span>>
<div class="modal-dialog"/span>>
<div class="modal-content bg-dark"/span>>
<div class="modal-header"/span>>
< h5 class="modal-title"/span> id="exampleModalLabel"/span>> 顯示值</h5>
< button type="button" class="btn-close btn- close-white btn-sm" data-bs-dismiss="modal" aria-label="Close" > </button>>
</div>
<div class="modal-body">
<form>/span>
<div class="mb-3">
<h1 className="text-white"/span>> {value}</h1>
{/*上述數值始終為零 */}。
</div>
</form>/span>
</div>/span>
</div>/span>
</div>/span>
</div>/span>
</>)。)
}
export default Comp;
對于陣列中的每個值0, 1, 2, 3, 4, 5,值被映射到每個按鈕,結果如下。
到目前為止,所有的按鈕都與它們相應的values正常顯示,如圖所示。但是當我打開模態時,只有一個值顯示出來,那就是0,而不管我點擊哪個按鈕。
在下面的圖片中,我點擊了value為3的按鈕,0顯示在模態中。
uj5u.com熱心網友回復:
這是因為你每次打開的都是同一個模態。按鈕的data-bs-target和模態的id必須是對應的和唯一的,所以帶0的按鈕打開一個帶0的模態,帶1的按鈕打開一個帶1的模態,以此類推 ... ↓↓↓
這是可選的,但你也需要將所有的class屬性改為className,并給每個迭代中渲染的包裝元素一個唯一的key屬性 <div key={"some_key_" index}>
import "././node_modules/bootstrap/dist/css/bootstrap.min.css"/span>。
import React from "././node_modules/react"/span>。
function Comp(props) {
return [0, 1, 2, 3, 4, 5]。] map((value, index) =>
<div key={"some_key_" index}>
<button
type="button"
className="btn btn-success m-2"
data-bs-toggle="modal"。
data-bs-target={"#exampleModal" index}。
>{`點擊按鈕${value}來打開下面的Modal`}</button>>
<div
className="modal fade text-white"
id={"exampleModal" index}。
data-bs-backdrop="static"。
tabIndex="-1"。
aria-labelledby={"exampleModalLabel" index}。
aria-hidden="true"。
>
<div className="modal-dialog"/span>>
<div className="modal-content bg-dark"/span>>
<div className="modal-head">
< h5 className="modal- title" id={"exampleModalLabel" index}>
顯示值
</h5>
<button
type="button"
className="btn-close btn-close-white btn-sm"
data-bs-dismiss="modal"
aria-label="Close"。
></button>>
</div>
<div className="modal-body">
<form>/span>
<div className="mb-3">
<h1 className="text-white"/span>> {value}</h1>。
</div>/span>
</form>
</div>/span>
</div>/span>
</div>/span>
</div>/span>
</div>
));
}
export default Comp;
在我的作業演示HERE中,我不得不從HTML屬性中洗掉所有的...-bs-...,因為我沒有使用任何這些屬性,但你有這個想法
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/326604.html
標籤:


