[英]How to get the name of Material UI 'Autocomplete' component?
I'm working with multiple Autocomplete MUI components and currently trying to write a "generic" event handler that will call useReducer
hook to store the state.我正在使用多个自动完成MUI 组件,目前正在尝试编写一个“通用”事件处理程序,该处理程序将调用useReducer
挂钩来存储 state。
The problem is that in Autocomplete
docs, onChange function looks like the following:问题是在Autocomplete
文档中,onChange function 如下所示:
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 Autocomplete is being changed), but event.target.name
and event.currentTarget.name
are not working.我正在尝试从事件 object 中获取字段的名称(以确定正在更改的自动完成),但event.target.name
和event.currentTarget.name
不起作用。
Are there are any ways to retrieve the name of a component that was changed?是否有任何方法可以检索已更改组件的名称?
The reason you get undefined is that the event.target
in the onChange
points to the li
but the MaterialUi Autocomplete will add the name
to the outer div
.您未定义的原因是onChange
中的event.target
指向li
但 MaterialUi Autocomplete 会将name
添加到外部div
。 So, there is no straight forward way.所以,没有直接的方法。 You can use a ref
and use getAttribute
to get the name.您可以使用ref
并使用getAttribute
来获取名称。
Code snippet代码片段
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"
/>
)}
/>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.