繁体   English   中英

下拉列表中的值似乎不会随着 onChange 处理程序而改变 - 使用 React 的 MUI Select

[英]Value inside dropdown doesn't seem to change with onChange handler - MUI Select using React

尝试使用 MUI 的Select组件更新下拉值,但我无法使用onChange处理程序进行更新,即使我 select 是下拉列表中的新项目,该value始终保持不变。

我使用CodeSanbox创建了一个工作示例。 有人可以帮忙吗?

摘自我的代码

export default function Cars() {
  const rows = [
    {
      make: "BMW",
      model: "X3",
      type: "Suv"
    },
    {
      make: "VW",
      model: "Jetta",
      type: "Sedan"
    }
  ];

  const handleChange = (e, row, index) => {
    console.log("dropdown value -> ", e.target.value);
    console.log("row -> ", row);
    row.type = e.target.value;
  };

  return (
    <div>
      <TableContainer>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Make</TableCell>
              <TableCell>Model</TableCell>
              <TableCell>Type</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map((row, index) => (
              <TableRow key={row.make}>
                <TableCell component="th" scope="row">
                  {row.make}
                </TableCell>
                <TableCell component="th" scope="row">
                  {row.model}
                </TableCell>
                <TableCell component="th" scope="row">
                  <FormControl>
                    <InputLabel>Type</InputLabel>
                    <Select
                      value={row.type}
                      label="Type"
                      onChange={(e) => handleChange(e, row, index)}
                    >
                      <MenuItem value="Sedan">Sedan</MenuItem>
                      <MenuItem value="Suv">Suv</MenuItem>
                    </Select>
                  </FormControl>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}

您应该使用useState来保留rows数据的当前 state 并更新您的handleChange function 中的数组,如下所示:

const [rows, setRows] = useState([
    {
      make: "BMW",
      model: "X3",
      type: "Suv"
    },
    {
      make: "VW",
      model: "Jetta",
      type: "Sedan"
    }
]);

const handleChange = (e, row, index) => {
    console.log("dropdown value -> ", e.target.value);
    console.log("row -> ", row);
    const copyRows = [...rows];
    copyRows[index].type = e.target.value;
    setRows(copyRows);
};

您可以查看这个分叉的沙箱以获取实时工作示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM