[英]React: TypeScript generics, auto switch parameter-type from function (function as props)
[英]Function to Handle Multiple Switch Controls in 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.