【问题标题】:MUI v5 - Can't access MenuItem attribute through event.currentTarget after updateMUI v5 - 更新后无法通过 event.currentTarget 访问 MenuItem 属性
【发布时间】:2021-11-30 22:21:47
【问题描述】:

我之前使用的是 v4,并且我的 Select 和 MenuItems 设置如下:

const [select, setSelect] = useState('');
const [customName, setCustomName] = useState('');

const handleChange = (event) => {
    setSelect(event.target.value);
    setCustomName(event.currentTarget.getAttribute('name'));
  };

...

                <Select
                  label="Choose A Dataset"
                  onChange={handleChange}
                  value={select}
                >
                  {tables &&
                    tables.map(
                      (table, index) =>
                          (
                          <MenuItem
                            key={table.name}
                            value={table.code}
                            name={table.name}
                          >
                            {table.name}
                          </MenuItem>
                        )
                    )}
                </Select>

我可以通过

访问menuItem的name属性
event.currentTarget.getAttribute('name');

但是,在迁移到 v5 之后,event.currentTarget 返回 null。有什么建议吗?

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    SelectInput 有这个onChange 定义:

    onChange?: (event: SelectChangeEvent<T>, child: React.ReactNode) => void;
    

    这意味着您可以将孩子作为handleChange 上的第二个参数点击。在这里,您可以使用child.props.name 访问名称属性。

    但是值得注意的是 MenuItem 没有 name 属性,如果你定义它,Typescript 会将它突出显示为错误。为避免这种情况,您可以使用event.target.value 来查找具有匹配code 的表并以这种方式获取名称:

    const name = tables.find((table) => table.code === event.target.value).name;
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2022-06-10
      • 2022-08-02
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      相关资源
      最近更新 更多