【问题标题】:How to get the name of Material UI 'Autocomplete' component?如何获取 Material UI 'Autocomplete' 组件的名称?
【发布时间】:2020-10-16 15:51:28
【问题描述】:

我正在使用多个Autocomplete MUI 组件,目前正在尝试编写一个“通用”事件处理程序,它将调用useReducer 挂钩来存储状态。

问题是在Autocomplete docs 中,onChange 函数如下所示:

function(event: object, value: T | T[], reason: string) => void

我正在尝试从事件对象中获取字段的名称(以确定正在更改的自动完成功能),但 event.target.nameevent.currentTarget.name 不起作用。

是否有任何方法可以检索已更改组件的名称?

【问题讨论】:

  • 你可以做onChange={callback.bind(null, <your-identifier-here>}

标签: javascript reactjs material-ui


【解决方案1】:

您未定义的原因是onChange 中的event.target 指向li,但MaterialUi 自动完成功能会将name 添加到外部div。所以,没有直接的方法。您可以使用refgetAttribute 来获取名称。

代码 sn-p

export default function ComboBox() {
  const ref0 = useRef();

  return (
    <Autocomplete
      id="combo-box-demo"
      ref={ref0}
      name="movies"
      options={top100Films}
      getOptionLabel={option => option.title}
      onInputChange={(e, v, r) => {
        const ev = e.target;
        if (r === "reset") console.log(ev, v, r);
      }}
      onChange={(e, v, r) => {
        console.log(ref0.current.getAttribute("name"));
      }}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField
          name="auto-input"
          {...params}
          label="Combo box"
          variant="outlined"
        />
      )}
    />
  );
}

【讨论】:

  • 在这个道具中 - ref={ref0} 是否可以选择您想要的任何 ref 名称?喜欢red={input} 或类似的?
  • 您是否得到了关于是否可以选择任何您想要的参考名称的答案?
猜你喜欢
  • 2020-02-28
  • 1970-01-01
  • 1970-01-01
  • 2022-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
  • 2020-03-14
相关资源
最近更新 更多