您好,我正在构建一个表单,我能够返回我的onchange和state的其他输入的值。但是,当我尝试实现开关时,我什么也得不到,甚至连true或false都没有得到。如何让开关在切换时返回yes或no标签?下面是我将使用的material-ui组件
material.js
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import FormGroup from '@material-ui/core/FormGroup';
import Switch from '@material-ui/core/Switch';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
export default function CustomizedSwitches() {
return (
<FormGroup>
<Typography component="div">
<Grid component="label" container alignItems="center" spacing={1}>
<Grid item>No</Grid>
<Grid item>
<AntSwitch />
</Grid>
<Grid item>Yes</Grid>
</Grid>
</Typography>
</FormGroup>
);
}下面是我如何处理表单中的输入
form.js
class App extends Component {
// constructor
constructor(props) {
super(props);
// initial state
this.state = {
formValues : {},//this is where i store my input values
};
// i use this to submit info
this.submitInformation = this.submitInformation.bind(this);
}
handleChange(event) {
event.preventDefault();
const isCheckbox = event.target.type==='checkbox'; //implementing this does not work why??
let formValues = this.state.formValues
let name = event.target.name;
let value = isCheckbox ? event.target.checked : event.target.value; //is the problem here??
formValues[name] = value
this.setState({formValues});
}
async submitInformation(event){
event.preventDefault();
alert('You have submitted the form.')
let sharePointStructure = {
response : this.state.formValues[false],
ToolName : this.state.formValues["ToolName"],
}
return (
<div className="App">
<div >
<form className="float-container" onSubmit = {this.submitInformation}>
<div>
<CustomizedSwitches
name="response"
onChange={this.handleChange.bind(this)}
checked={this.state.formValues["response"]}/>
</div>
<form/>
</div>)
发布于 2020-12-08 02:53:08
您正在改变状态,这可能会导致一些问题。通过制作状态的浅层副本来尝试此操作:
handleChange(event) {
event.preventDefault();
const isCheckbox = event.target.type==='checkbox'; //implementing this does not work why??
let formValues = {...this.state.formValues} //make a shallow copy of formValues
let name = event.target.name;
let value = isCheckbox ? event.target.checked : event.target.value; //is the problem here??
formValues[name] = value // then mutate the copied state
this.setState({formValues});
}https://stackoverflow.com/questions/65174527
复制相似问题