我正在尝试从表单中动态收集输入数据,而不是键入每个单独的输入字段名称。 使用标准 React 这很容易,但是我正在切换到 React Hooks,现在我对如何实现相同的目标有点困惑。
const gatherFormData = e => {
if (e.target.value !== null) {
_.assign(
formData.payload,
{ [e.target.name]: e.target.value, action },
{ groupNumber },
);
setState({
[e.target.name]: (e.target.value),
formData
});
}
};
我尝试使用模板文字语法,但这不起作用。
set`${e.target.name}`(e.target.value);
您可以将
useState
与对象一起使用,以便您可以动态添加内容。例:
const [targets, setTargets] = useState({});
// Set values like this
setTargets({...targets, [`${e.target.name}`]: e.target.value});
// Then get values:
const theValue = targets.yourTargetNameHere
设置值时,必须使用展开语法({...targets
(来维护放入对象中的其他值。
import React, { useState } from "react";
function App() {
const [inputList, setInputList] = useState([{ firstName: "", lastName: "" }]);
return (
<div className="App">
<h3><a href="https://cluemediator.com">Clue Mediator</a></h3>
{inputList.map((x, i) => {
return (
<div className="box">
<input
name="firstName"
value={x.firstName}
/>
<input
className="ml10"
name="lastName"
value={x.lastName}
/>
<div className="btn-box">
{inputList.length !== 1 && <button className="mr10">Remove</button>}
{inputList.length - 1 === i && <button>Add</button>}
</div>
</div>
);
})}
<div style={{ marginTop: 20 }}>{JSON.stringify(inputList)}</div>
</div>
);
}
export default App;
我希望使用按钮动态添加新的输入字段,并使用状态跟踪这些输入字段。这就是我解决这个问题的方式。
const [newMembers, setNewMembers] = useState(['']);
const addAnotherMember = () => {
setNewMembers(state => [...state, '']);
};
const handleChange = (e: any, i: any) => {
const email = e.target.value;
setNewMembers(state => [...state.slice(0, i), email, ...state.slice(i + 1)]);
};
const handleRemove = (index: any) =>
setNewMembers(state => [...state.slice(0, index), ...state.slice(index + 1)]);
enter code here
return ( <div>
{newMembers.map((item, i) => {
return (
<div className="relative ">
<FormInput
label="Email address"
type="text"
value={newMembers[i]}
setValue={setValue}
onChange={(e: any) => {
handleChange(e, i);
enableButton();
}}
/>
{i > 0 ? (
<span
className="absolute subdomain__mask cursor-pointer"
onClick={() => {
handleRemove(i);
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-20 w-20"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
strokeWidth="2"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</span>
) : null}
</div>);