You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React使用.map()渲染Bootstrap Modal子组件时Modal内部props取值异常如何解决

问题原因

你遇到的问题核心是所有生成的Child组件共用了相同的HTML id属性。Bootstrap原生模态框的触发逻辑是通过data-bs-target属性匹配页面上对应id的DOM元素,只会匹配到第一个出现的id为exampleModal的模态框,也就是对应monthpassed为0的第一个Child组件实例,因此无论点击哪个按钮,弹出的都是第一个模态框,显示值自然始终为0。

解决方案

用传入的monthpassed作为唯一标识,动态拼接所有和模态框关联的id属性即可,修改后的Child组件代码如下:

import "../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import React from "../../node_modules/react";

function Child(props) {
  // 生成当前组件独有的id前缀
  const modalId = `exampleModal-${props.monthpassed}`;
  const modalLabelId = `exampleModalLabel-${props.monthpassed}`;
  return (
    <>
      <h1 className="text-white">{props.monthpassed}</h1>
      <button type="button" className="btn btn-success" data-bs-toggle="modal" data-bs-target={`#${modalId}`}>
        Click to open below Modal
      </button>

      <div className="modal fade text-white" id={modalId} data-bs-backdrop="static" tabindex="-1" aria-labelledby={modalLabelId} aria-hidden="true">
        <div className="modal-dialog">
          <div className="modal-content bg-dark">
            <div className="modal-header">
              <h5 className="modal-title" id={modalLabelId}>Select project and add an allocation</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">{props.monthpassed}</h1>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </>);
}

export default Child;

另外注意React中HTML的class属性需要写成className,否则会触发属性不匹配的警告,上述代码已同步修正该问题。

修改后每个Child组件的模态框id都是唯一的,点击按钮时会触发对应id的模态框,即可显示匹配的monthpassed值。


内容的提问来源于stack exchange,提问作者kaushalpranav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 02:39:05