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

I'm working with multiple Autoplete MUI ponents and currently trying to write a "generic"

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"
        />
      )}
    />
  );
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744247733a4565018.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信