【问题标题】:The values iterated by .map() do not reflect inside the function in html attribute.map() 迭代的值不会反映在 html 属性中的函数内部
【发布时间】:2021-11-12 08:40:00
【问题描述】:

Parent 组件中,传递[0, 1, 2, 3, 4, 5] 值,并为每个值创建一个Child 组件。所以Child 组件出现了 6 次。子组件是 bootstrap modal 如下

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

function Child(props) {
  return (
    <>
      <h1 className="text-white">{props.monthpassed}</h1>
      <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#exampleModal">
        Click to open below Modal
      </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">Select project and add an allocation</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">{props.monthpassed}</h1>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </>);
}

export default Child;

请注意,props.monthpassed 存在两个实例。一次在按钮上方,一次在单击该按钮时将显示的实际模式上。

Parent 组件如下。

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

function Parent(props) {
  return [0, 1, 2, 3, 4, 5].map(xx => <Child monthpassed={xx}></Child>);
}

export default Parent;

显示父组件时,如下图所示。

请注意,在每个按钮上方,传递的props.monthpassed 会根据Parent 组件中数组中的值正确显示。这非常有效。

但是,当我单击任何按钮时,模态框仅在模态框内显示一个值 0,而不是在父组件中显示的数组中的值。

我该如何处理这种差异?

【问题讨论】:

    标签: reactjs twitter-bootstrap bootstrap-modal bootstrap-5 react-state


    【解决方案1】:

    你忘了写地图的回报。

    months.map((month, month_idx) => {
        return (
            <ProjectSelectionModal
                key={month_idx}
                onSelectingProject={(project) => selectProjectHandler(month_idx)}>
            </ProjectSelectionModal>
        );
    });
    

    【讨论】:

    • 糟糕。我的错,那里没有大括号,这是从地图直接返回的。我已经更新了问题。
    • 在这种情况下,您可能需要向我们展示selectProjectHandler 函数是什么。因为问题不够清楚。
    • 我并没有完全理解错误。我已经用完整的细节更新了这个问题,因为我发现模态导致了问题,而我一直忽略了这个问题。
    猜你喜欢
    • 2011-06-03
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2014-10-21
    • 2020-10-08
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    相关资源
    最近更新 更多