一次清除所有表单字段,reactjs

时间:2019-05-14 06:43:57

标签: reactjs

我想在单击表单中的“重置”按钮时清除所有字段。我怎么能够   使用状态吗?我正在使用材料ui主题。我不想设定状态    个别地。那可能吗?

``````````````````````````````````
 <form className={classes.form}>
      <FormControl margin="normal" required fullWidth>
        <InputLabel htmlFor="Name">Name</InputLabel>
        <Input id="name" name="name" autoComplete="name" autoFocus />
      </FormControl>
      <div className ='switchdesign'>
       <FormControlLabel   required 
          label="Private ? "
          labelPlacement="start"
              control={
                <Switch
                  checked={this.state.checkedA}
                  onChange={this.handleChange('checkedA')}
                  value="checkedA" />
              } />
        </div>
      <div className ='switchdesign'>
          <FormControl className={classes.formControl}>
      <Select
        labelPlacement="start"
        value={this.state.age}
        onChange={this.onhandleChange}
        name="tenant"
        displayEmpty
        className={classes.selectEmpty}
      >
        <MenuItem value="" disabled>
          Choose Option
        </MenuItem>
        <MenuItem value="a">A</MenuItem>
        <MenuItem value="b">B</MenuItem>
        <MenuItem value="c">C</MenuItem>
      </Select>
      <FormHelperText>Tenant</FormHelperText>
    </FormControl>
      </div>

      <Button
        type="reset"
        fullWidth
        variant="contained"
        color="primary"
        className={classes.submit}
      >
        Reset
      </Button>

      <Button
        type="submit"
        fullWidth
        variant="contained"
        color="primary"
        className={classes.submit}
      >
        Submit
      </Button>
    </form>
``````````````````````````````````````````````````````

我需要强制使用裁判吗?这是更好的方法吗?或使用    状态更好?

1 个答案:

答案 0 :(得分:0)

您可以通过将初始状态设置为变量然后按如下所示重置它来实现

class MyComponent extends Component {
    static initialState = {
       // your object state
    }

    constructor(props) {
        super(props)

        //set your state here when init component
        this.state = {
        }
    }

    resetForm() {
        this.setState(initialState)
    }
}

让我知道您是否仍然有问题