首页 > 解决方案 > 按下按钮后无法清除输入字段

问题描述

class CategoryBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      newCategoryTitle: '',
      errorMsg: null,
      updateCategoryTitle: '',
    };
    this.handleCreateCategory = this.handleCreateCategory.bind(this);
    this.handleUpdateCategory = this.handleUpdateCategory.bind(this);
  }
  ...
  ...
  handleUpdateCategory(e) {
    e.preventDefault();
    this.setState({
      updateCategoryTitle: ''
    });
  }
  render() {
    return (
    //...
    <form>
      <input
        type={'text'}
        className={styles.tabSmallField}
        placeholder={ category.name }
        onChange={(e) => { this.setState({ updateCategoryTitle: e.target.value }); }} />
      <button type="submit" onClick={this.handleUpdateCategory}>Update</button>
    </form>
    //...
  }
}

我想在按下按钮后清除输入文本字段。

看起来它在按下按钮后进入“handleUpdateCategory(e)”。但它不会清除按钮上方的输入字段。

如何清除输入文本字段?

标签: reactjs

解决方案


答案在评论中。

It didn't clear because you never bind the state value to your <input>. Change it like this <input value={this.state.updateCategoryTitle} ...other props... />

推荐阅读