javascript - 在 React/Typescript 中处理多个开关控件的函数
问题描述
我想要做的是发送多个开关控制的发布请求,但是我认为它们必须是一种更简单的方法来发送请求,而不是单独为每个开关输入编写请求。我怎样才能整合或编写一个可以干净地做到这一点的函数?使用打字稿/反应。问题更新如下:
UPDATE: What I want to do is send the state of the switch input control as a toggle. ie. when the switch control is set to yes/no, then it sends a post request to the server
interface IState {
checkedA?: boolean;
checkedB?: boolean;
}
public render() {
const {} = this.state;
<div className={classes.switchContainer}>
<FormGroup row>
<FormControlLabel
control={
<Switch
checked={this.state.checkedA}
onChange={this.handleChange}
value="checkedA"
>Toggle</Switch>
}label="YES"
/>
<Typography color="secondary" variant="body1" className={classes.toggleQuestions}>Question 1</Typography>
</FormGroup>
</div>
<div className={classes.switchContainer}>
<FormGroup row>
<FormControlLabel
control={
<Switch
checked={this.state.checkedB}
onChange={this.handleChange}
value="checkedB"
>Toggle</Switch>
}label="YES"
/>
<Typography color="secondary" variant="body1" className={classes.toggleQuestions}>Question 2</Typography>
</FormGroup>
</div>
)}
<Button
onClick={this.submitRecommendation}>
Send Request</Button
await axios.post(
`/test/testpost`,
{
post request from click of button would go in here
} catch (err) {
}
);
解决方案
下面是一个示例,说明如何在表单提交时以编程方式访问输入:
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
推荐阅读
- c - 如何将 2 个数组传递给一个函数,让用户在这 2 个数组中写一些东西,并将它们都返回给 C 中的程序?
- r - 根据 R 中的多个 ffields 比较列值中的字符串值
- bash - 在bash中对数组进行数字排序
- c# - C# Excel VSTO OLE DB 参数错误必须声明标量变量
- git - 在将我的分支与本地仓库中的 Master 合并,然后在 Github 中推送到远程源
- c# - 如何在我的 Discord Bot 中使用数据库?(使用 Discord.Net 和 psotgresql)
- r - 如何在 R 中使用 tidyeval 创建一个包含所有级别因子的小型预测数据集?
- c++ - Qt RegExp 验证器 C++
- scala - 我如何通过字段相等来匹配scala中的两个集合
- python - TypeError:尝试将数组与列表进行比较时,“numpy.ndarray”和“str”的实例之间不支持“>”