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

标签 javascript node.js reactjs ecmascript-6 single-page-application

我想在单击表单中的重置按钮时清除所有字段。我怎么能够 使用状态来做吗?我正在使用 Material 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>

我需要强制使用引用吗?这是更好的方法吗?或使用 州比较好?

最佳答案

您可以通过将初始状态设置为变量然后像这样重置它来做到这一点

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)
    }
}

如果您仍有问题,请告诉我

关于javascript - 一次清除所有表单字段,reactjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56124420/

相关文章:

javascript - 如何扩展 Sequelize 模型

javascript - react 状态定义为属性深度克隆返回 'is undefined'

javascript - React App : EventSource's response has a MIME type ("application/json") that is not "text/event-stream". 中止连接

javascript - 我正在尝试使用 angularjs 切换表格单元格中的值...我可以使用 ngbind 或 ngmodel 或其他东西吗?

javascript - 现代最流行的 ajax 框架是什么?

node.js - 谁可以在bluehost中访问nodejs应用程序?

javascript - 如何使用 node-mongodb-native 连接到 Modulus.io?

JavaScript 数组澄清

javascript - 文件上传 - Node Js(Express) 到 React Js。如何获取正确的图片路径?

javascript - 为什么新的 javascript 数组有 'undefined' 个条目?