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

React使用MUI Select组件时onChange无法更新下拉框值问题

问题修复方案

核心问题

  • 你没有将表格数据rows声明为React的响应式状态,直接定义为组件内的普通变量,每次组件重渲染都会重置为初始值
  • 直接修改原row对象的属性,不符合React不可变更新的规范,无法触发组件重渲染,因此Select绑定的value始终不会更新

修正后代码

import { useState } from 'react';
import { TableContainer, Table, TableHead, TableRow, TableCell, TableBody, FormControl, InputLabel, Select, MenuItem } from '@mui/material';

export default function Cars() {
  // 将rows定义为响应式状态
  const [rows, setRows] = useState([
    {
      make: "BMW",
      model: "X3",
      type: "Suv"
    },
    {
      make: "VW",
      model: "Jetta",
      type: "Sedan"
    }
  ]);

  const handleChange = (e, index) => {
    const newType = e.target.value;
    // 不可变方式更新状态,触发组件重渲染
    setRows(prevRows => {
      const updatedRows = [...prevRows];
      updatedRows[index] = { ...updatedRows[index], type: newType };
      return updatedRows;
    });
  };

  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, index)}
                    >
                      <MenuItem value="Sedan">Sedan</MenuItem>
                      <MenuItem value="Suv">Suv</MenuItem>
                    </Select>
                  </FormControl>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:24:06