首页 > 解决方案 > 使用ant design在react js中映射元素

问题描述

大家好,我在 ant-design 中映射模态时遇到问题

  import React, { useState } from "react";
    import { Modal } from "antd";
    import "./style.css";
    import "antd/dist/antd.css";
    export default function App() {
      const arr = [
        {
          name: "siddharth",
          id: 32
        },
        {
          name: "sanjay",
          id: 34
        }
      ];
      
      const [modalstate, setModalstate] = useState({
        edit: false,
        remove: false
      });
      return (
        <div>
          <h1>Hello StackBlitz!</h1>
          <p>Start editing to see some magic happen :)</p>
          {arr.map(x => (
            <>
              <div>
                {x.name}
    
                <button
                  onClick={() => setModalstate({ ...modalstate, edit: true })}
                >
                  Edit
                </button>
                <button
                  onClick={() => setModalstate({ ...modalstate, remove: true })}
                >
                  Remove
                </button>
              </div>
              <Modal
                visible={modalstate.edit}
                onCancel={() => setModalstate({ ...modalstate, edit: false })}
              >
                {x.name}
                {"EDIT "}
              </Modal>
              <Modal
                visible={modalstate.remove}
                onCancel={() => setModalstate({ ...modalstate, remove: false })}
              >
                {x.name}
                {"REMOVE"}
              </Modal>
            </>
          ))}
        </div>
      );
    }

在此代码中,问题是当我单击第一项按钮时,编辑/删除它会为第二项打开。因此,每个组件的模态都没有被渲染,只有最后一个被渲染 https://react-vzh4yd.stackblitz.io

标签: javascriptarraysreactjsantd

解决方案


推荐阅读