最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the name of Material UI 'Autocomplete' component? - Stack Overflow

programmeradmin5浏览0评论

I'm working with multiple Autoplete MUI ponents and currently trying to write a "generic" event handler that will call useReducer hook to store the state.

The problem is that in Autoplete docs, onChange function looks like the following:

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

I'm trying to get the name of a field from the event object (to determine what Autoplete is being changed), but event.target.name and event.currentTarget.name are not working.

Are there are any ways to retrieve the name of a ponent that was changed?

I'm working with multiple Autoplete MUI ponents and currently trying to write a "generic" event handler that will call useReducer hook to store the state.

The problem is that in Autoplete docs, onChange function looks like the following:

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

I'm trying to get the name of a field from the event object (to determine what Autoplete is being changed), but event.target.name and event.currentTarget.name are not working.

Are there are any ways to retrieve the name of a ponent that was changed?

Share Improve this question asked Jun 26, 2020 at 4:29 KarenKaren 1,4295 gold badges27 silver badges50 bronze badges 1
  • 1 You could do onChange={callback.bind(null, <your-identifier-here>}. – hotpink Commented Jun 26, 2020 at 4:55
Add a ment  | 

1 Answer 1

Reset to default 4

The reason you get undefined is that the event.target in the onChange points to the li but the MaterialUi Autoplete will add the name to the outer div. So, there is no straight forward way. You can use a ref and use getAttribute to get the name.

Code snippet

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

  return (
    <Autoplete
      id="bo-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"
        />
      )}
    />
  );
}
发布评论

评论列表(0)

  1. 暂无评论