Хорошо, вот пример того, как вы можете получить программный доступ ко входам при отправке формы:
private handleSubmit = (e: React.FormEvent): void => {
e.preventDefault();
// We want the form as a starting point to traverse the DOM
const form = e.target;
// It seems like we can be relatively sure that all the information
// we want is contained in the form's inputs, so we'll select them all
const inputs = form.querySelectorAll('input');
// With the NodeList inputs (a DOM data type), we can use .forEach
// to check out all the nodes by their type
inputs.forEach(input => {
// Accessing the name and value will give you all
// the information you need to build up a POST request
switch(input.type) {
case 'checkbox':
console.log('The checkbox is called', input.name, 'and its checked state is', input.checked);
break;
case 'text':
console.log('The text input is called', input.name, 'and it says', input.value);
break;
}
});
}
И вот пример того, как вы могли бы потенциально создать объект запроса в цикле .forEach, создав объект для отправки в вашем запросе. Вы можете сделать это довольно легко, если убедитесь, что используете правильное название для каждого предмета.
// in the above method
const request = {};
inputs.forEach(input => {
// Somehow map the input name and value to your data model you're updating
request[input.name] = input.value;
});
await axios.post(/* use request object here */);
Надеюсь, этого достаточно, чтобы начать, но не стесняйтесь комментировать, если есть какие-то конкретные детали реализации, которые вы хотели бы обсудить! : D