在此问题之后,我想替换 TextField(输入年龄)组件以使用 Select 组件,因为我注意到它们都具有 inputProps 属性。
原始应用程序:
function App() {
const [state, setState] = React.useState({
cats: [{ name: "cat1", age: "2" }, { name: "cat2", age: "5" }],
owner: "Owner's Name"
});
const handleFormChange = e => {
if (["name", "age"].includes(e.target.dataset.fieldType)) {
const newCats = [...state.cats];
newCats[e.target.dataset.id][e.target.dataset.fieldType] = e.target.value;
setState({ ...state, cats: newCats });
} else {
setState({ ...state, [e.target.name]: e.target.value });
}
};
return (
<form onChange={handleFormChange}>
<TextField label="Owner" value={state.owner} name="owner" />
<br />
<br />
<TextField
label="Name 1"
value={state.cats[0].name}
inputProps={{ "data-id": 0, "data-field-type": "name" }}
/>
<TextField <-----------------------replace with a Select
label="Age 1"
value={state.cats[0].age}
inputProps={{ "data-id": 0, "data-field-type": "age" }}
/>
</form>
);
}
我要替换第二个 TextField 的 Select 组件:
<Select
onChange={handleSelectChange}
label={"Age 1"}
value={state.cats[0].age}
inputProps={{
"data-id": idx,
"data-field-type": "age",
name: "customName"
}}
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
但是在我的 handleSelectChange 函数中:
const handleSelectChange = e => {
console.log("value", e.target.value); //OK
console.log("name", e.target.name); // OK
console.log("dataset", e.target.dataset); //undefined
};
传递给 inputProps 的数据属性是未定义的,这是为什么呢?
这是我测试此行为的代码和框:https ://codesandbox.io/s/dynamic-form-change-handler-with-select-ft4dj