gpt4 book ai didi

javascript - 通过 onFocus 属性中的事件对象获取 TextField(作为选择框)Material-UI 的名称属性

转载 作者:行者123 更新时间:2023-12-05 00:37:57 27 4
gpt4 key购买 nike

我一直在使用"@material-ui/core": "4.11.2""react": "16.8.6" 打包.在 TextField组件当select Prop 是 true ,我无法获取 name TextField 的属性(property)来自 event handleFocus 中的对象功能。

<TextField
id="standard-select-currency"
name="mySelectBox"
select
label="Select"
value={currency}
onChange={handleChange}
onFocus={handleFocus}
helperText="Please select your currency"
>
{currencies.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
这里是 handleFocushandleChange功能。
  const handleChange = (event) => {
console.log(
"event.target ==>",
event.target,
"event.target.name ==>", // mySelectBox
event.target.name
);
};

const handleFocus = (event) => {
console.log(
"event.target ==>",
event.target,
"event.target.name ==>", // undefined
event.target.name
);
};
我在 this sandbox 中创建了一个完整的示例.

最佳答案

Texfield 不直接将 onFocus 传递给输入。来自 MUI ,

The ref is forwarded to the root element.

Any other props supplied will be provided to the root element(FormControl).

onFocus传递给 FormControl 元素,它是一个 div,不是输入,也没有名称。您可以使用 NativeSelect或将 onFocus 属性传递给输入 Prop ,当我在您提供的沙箱中尝试时效果不佳。
最快的解决方案是将引用传递给输入,并在焦点上从引用中获取名称。这就是你的代码的样子。
export default function MultilineTextFields() {
const [currency, setCurrency] = React.useState("EUR");
const inputRef = React.useRef()

const handleChange = (event) => {
setCurrency(event.target.value);
console.log(
"event.target ==>",
event.target,
"event.target.name ==>",
event.target.name
);
};

const handleFocus = (event) => {
console.log(
"event.target ==>",
inputRef,
"event.target.name ==>",
inputRef.current.node.name
);
};

return (
<form noValidate autoComplete="off">
<TextField
inputRef= {inputRef}
id="standard-select-currency"
name="mySelectBox"
select
label="Select"
value={currency}
onChange={handleChange}
onFocus={handleFocus}
helperText="Please select your currency"
>
{currencies.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
</form>
);
}
这是我使用的沙箱 https://codesandbox.io/s/material-demo-forked-zjlz3?file=/demo.js

关于javascript - 通过 onFocus 属性中的事件对象获取 TextField(作为选择框)Material-UI 的名称属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70913139/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com