动态插入具有事件属性的 属性
Dynamically inserting a property with event properties
我正在尝试为输入数组创建通用处理程序。在我的状态下,我的属性是数组,如下所示:
const [state, useState] = useState({
arr1: [''],
arr2: [''],
arr3: ['']
});
const handleArrayChange = (index, e) => {
const val = [...state.[e.target.name]];
val[index] = e.target.value;
setState({...state, [e.target.name]: [...val]})
};
然后,我的输入字段使用Material UI TextFields,用户可以动态添加更多字段:
const array1List = [...state.arr1].map((item, index) => (
<TextField name='arr1' onChange={(e) => handleArrayInputs(index, e)} variant='outlined' ... />
//Some button that will add more fields
));
const array2List = [...state.arr2].map((item, index) => (
<TextField name='arr2' onChange={(e) => handleArrayInputs(index, e)} variant='outlined' ... />
//Some button that will add more fields
));
....
这适用于 this codesandbox。但是,我在 [...data.[e.target.name]]
上的编辑器中得到了一个 Parsing error
eslint。我不明白为什么它在 codesandbox 中有效但在我的编辑器中无效。
I don't get the problem why it works in codesandbox but not in my editor.
好吧,你的编辑器并没有做任何事情来真正使代码工作,它只是编辑文本。
ESlint 解析器在 data.[e.target.name]
上阻塞,在我看来这是无效的 JavaScript 语法(data[e.target.name]
是正确的),但出于某种原因,Babel 转译器是 Codesandbox [=13] =].
很可能它可以与您在本地使用的任何转译工具一起正常工作(可能是 Create React App,所以它在 Webpack 中是 Babel 运行),但 ESlint 不喜欢它。
我正在尝试为输入数组创建通用处理程序。在我的状态下,我的属性是数组,如下所示:
const [state, useState] = useState({
arr1: [''],
arr2: [''],
arr3: ['']
});
const handleArrayChange = (index, e) => {
const val = [...state.[e.target.name]];
val[index] = e.target.value;
setState({...state, [e.target.name]: [...val]})
};
然后,我的输入字段使用Material UI TextFields,用户可以动态添加更多字段:
const array1List = [...state.arr1].map((item, index) => (
<TextField name='arr1' onChange={(e) => handleArrayInputs(index, e)} variant='outlined' ... />
//Some button that will add more fields
));
const array2List = [...state.arr2].map((item, index) => (
<TextField name='arr2' onChange={(e) => handleArrayInputs(index, e)} variant='outlined' ... />
//Some button that will add more fields
));
....
这适用于 this codesandbox。但是,我在 [...data.[e.target.name]]
上的编辑器中得到了一个 Parsing error
eslint。我不明白为什么它在 codesandbox 中有效但在我的编辑器中无效。
I don't get the problem why it works in codesandbox but not in my editor.
好吧,你的编辑器并没有做任何事情来真正使代码工作,它只是编辑文本。
ESlint 解析器在 data.[e.target.name]
上阻塞,在我看来这是无效的 JavaScript 语法(data[e.target.name]
是正确的),但出于某种原因,Babel 转译器是 Codesandbox [=13] =].
很可能它可以与您在本地使用的任何转译工具一起正常工作(可能是 Create React App,所以它在 Webpack 中是 Babel 运行),但 ESlint 不喜欢它。