简体   繁体   English

提交表单后清空 Material-UI 文本字段

[英]Empty Material-UI textfield after submitting the form

How can I clear value from the TextField after submitting the form?提交表单后如何从 TextField 中清除值? All of the components in the code are functional components, not the class ones.代码中的所有组件都是功能组件,而不是 class 组件。 Here is one of the TextFields, the others are similar to this one.这是其中一个 TextFields,其他与此类似。 I can make the type='search' as in the code bellow but then a user needs to press a button to clear the value and even then the error check is complaining about the field being empty.我可以在下面的代码中设置 type='search' 但是用户需要按下一个按钮来清除该值,即使这样,错误检查也会抱怨该字段为空。 Would it be better to try and refresh the component?尝试刷新组件会更好吗? This form is in a sidebar in my app.此表单位于我的应用程序的侧边栏中。

<form onSubmit={onSubmitHandler} className={classes.root}>
  <TextField
    name='firstName'
    inputRef={register({
      required: "Please enter first name",
      validate: value => isEmpty(value)
    })}
    label={translate('invitation.first_name')}
    error={!!errors.firstName}
    type='search'
    autoFocus
    fullWidth
  />

There is a value property that you have to pass to the TextField component.您必须将一个 value 属性传递给 TextField 组件。 check example below:检查下面的示例:

class SomeComponent extends Component {
  state = {value: ''}
  resetValue = () => {
    this.setState({value: ''});
  }
  render() {
    return (
      <div>
        <TextField
          ...
          value={this.state.value}
        />
        <button onClick={this.resetValue}>Reset</button>
      </div>
    )
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM