我有一个Comp组件,它所做的是显示一个6倍的按钮,打开一个模式。下面是它的代码。
import "../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import React from "../../node_modules/react";
function Comp(props) {
return [0, 1, 2, 3, 4, 5].map(value =>
<>
<button type="button" class="btn btn-success m-2" data-bs-toggle="modal" data-bs-target="#exampleModal">
{`Click button ${value} to open below Modal`}
{/* The value in the above line is working perfectly fine */}
</button>
<div class="modal fade text-white" id="exampleModal" data-bs-backdrop="static" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content bg-dark">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Show value</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>
<div class="mb-3">
<h1 className="text-white">{value}</h1>
{/* The above value is always zero */}
</div>
</form>
</div>
</div>
</div>
</div>
</>);
}
export default Comp;
对于数组中的每个值0 1 2 3 4 5,值被映射到每个按钮,结果如下所示。
到现在为止,所有的按钮都以其对应的值正常显示,如图所示。但当我打开模态时,只有一个值出现,不管我点击哪个按钮,它都是0。
在下面的图像中,我点击的按钮值为3和0显示在模式中。
###这是因为你每次都打开相同的模式。按钮的data-bs-target
and modal's id
must be corresponding and unique so the button w和模态的id
must be corr必须是对应且唯一的,所以带有0的按钮打开带有0的模态,带有1的按钮打开带有1的模态,以此类推。↓↓↓
这是可选的,但您还需要将所有类属性更改为className,并为在每次迭代
中呈现的包装元素指定一个惟一的key属性
import "../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import React from "../../node_modules/react";
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}
>{`Click button ${value} to open below 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">
<div className="modal-content bg-dark">
<div className="modal-header">
<h5 className="modal-title" id={"exampleModalLabel" + index}>
Show value
</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>
<div className="mb-3">
<h1 className="text-white">{value}</h1>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
));
}
export default Comp;
在我的工作演示这里,我必须删除所有…-b -…从HTML属性中提取因为我没有用到这些但你们已经知道了
阅读全文
▼ 版权说明