const [firstName, setFirstName] = useState<string>('');
const [lastName, setLastName] = useState<string>('');
const [dept, setDept] = useState<string>('');
const [login, setLogin] = useState<string>('');
const onChangeFirstName = (event: React.ChangeEvent<HTMLInputElement>) => {
setFirstName(event.target.value);
};
const onChangeLastName = (event: React.ChangeEvent<HTMLInputElement>) => {
setLastName(event.target.value);
};
const onChangeDept = (event: React.ChangeEvent<HTMLInputElement>) => {
setDept(event.target.value);
};
const onChangeLogin = (event: React.ChangeEvent<HTMLInputElement>) => {
setLogin(event.target.value);
};
<CustomTextField
onChange={onChangeDept}
</CustomTextField>
<CustomTextField
onChange={onChangeLogin}
</CustomTextField>
<CustomTextField
onChange={onChangeFirstName}
</CustomTextField>
<CustomTextField
onChange={onChangeLastName}
</CustomTextField>
interface IFormData {
firstName: string;
lastName: string;
}
const [ formData, setFormData ] = React.useState<IFormData>({
firstName: '',
lastName: '',
});
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setFormData({
...formData,
[e.target.name]: e.target.value,
});
<CustomTextField name="firstName" value={formData.firstName} onChange={onChange} />
<CustomTextField name="lastName" value={formData.lastName} onChange={onChange} />
<!-- или -->
{Object.entries(formData).map(([ k, v ]) => (
<CustomTextField key={k} name={k} value={v} onChange={onChange} />
))}
// хелперы
const makeCustomTextFieldWithState = (): [string, ReactElement] => {
const [value, setValue] = useState<string>('');
const onChange = (event: React.ChangeEvent<HTMLInputElement>) =>
setValue(event.target.value);
return [value, <CustomTextField onChange={onChange} />];
};
const makeManyCustomTextFieldWithState = (count: number): [string[], ReactElement[]] =>
Array(count).fill(0).reduce(([values, elements]) => {
const [value, element] = makeCustomTextFieldWithState();
return [
[...values, value],
[...elements, element],
];
}, [[], []]);
// в компоненте
const [[dept, login, firstName, lastName], elements] = makeManyCustomTextFieldWithState(4);
<>{elements}</>