簡體   English   中英

渲染組件數組時,單擊按鈕時,始終會選取數組的最新元素

[英]When rendering an array of components, when a button is clicked always the latest element of the array is picked up

有人可以提供一個深入的解釋,為什么這樣的事情在 React 中不起作用? 發生的情況是,每次單擊按鈕時,都會從數組中的最后一個元素中選取值“名稱”。 因此,在以下示例中,對話框將始終顯示名稱“John2”。

import React from "react";
import ReactDOM from "react-dom";
import { Dialog, DialogContent } from "@material-ui/core";

function Employee({ name, dialogOpen, setDialogOpen }) {
  const aDialog = () => {
    return (
      <Dialog open={dialogOpen}>
        <DialogContent>{name}</DialogContent>
      </Dialog>
    );
  };
  const handleClick = () => {
    setDialogOpen(true);
    aDialog();
  };

  return (
    <React.Fragment>
      {aDialog()}
      <button onClick={handleClick}>{name}</button>
    </React.Fragment>
  );
}

function App() {
  const employeeNames = ["John", "John1", "John2"];
  const [dialogOpen, setDialogOpen] = React.useState(false);
  return (
    <div className="App">
      {employeeNames.map(name => (
        <Employee
          name={name}
          dialogOpen={dialogOpen}
          setDialogOpen={setDialogOpen}
        />
      ))}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


在這里,我認為所有三個對話框都作為所有三個對話框的true值傳遞。 嘗試為每個名稱使用一些 id 或將其自身命名為 id。 IE

  const [dialogOpen, setDialogOpen] = React.useState(null);

並嘗試打電話

setDialogOpen(name);

並使用給定的邏輯傳遞真假

   <Employee
      name={name}
      dialogOpen={name===dialogOpen}
      setDialogOpen={setDialogOpen}
    />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM