【问题标题】:Input doesn't clear content even after state is modified in React即使在 React 中修改状态后,输入也不会清除内容
【发布时间】:2019-09-19 22:04:03
【问题描述】:

我有一个输入字段,旁边有一个“关闭 (x)”图标。当输入字段中的值发生变化时,我正在处理状态,一旦用户点击 Enter 我清除状态中的值。但是,在重新渲染之后(由于状态变化),先前的输入仍然保留在输入字段中。

constructor(props) {
    super(props);
    this.state = {
      filterSearchQuery: null, filterSearch: null}

    this.handleSearchInput = this.handleSearchInput.bind(this);
    this.handleSearchReset = this.handleSearchReset.bind(this);
}

handleSearchInput(e) {
     //   e.preventDefault();
    let val = e.target.value;
    if (e.keyCode == 13)
      this.setState({ entries: [], filterSearchQuery: null, filterSearch: val, pageIndex: 0, hasMore: false }, this.loadEntries);
    else
      this.setState({ filterSearchQuery: val });
}

handleSearchReset(e) {
    //e.preventDefault();
    this.setState({ entries: [], pageIndex: 0, hasMore: false, filterSearchQuery: null, filterSearch: null }, this.loadEntries);
}

渲染并返回:

<input type="text" className="outline-none flex-fill pt-0_2em pb-0_2em border-white border-none bg-color-white color-black font-12px font-weight-bold opacity-0_9" value={this.state.filterSearchQuery} placeholder="Search in results." onKeyUp={(e) => this.handleSearchInput(e)} onChange={(e) => this.handleSearchInput(e)} autoFocus={true} />
{
    (this.state.filterSearchQuery && this.state.filterSearchQuery.length > 0) &&
    <div className="">
    <button type="button" className="close" aria-label="Close" onClick={this.handleSearchReset}>
        <span aria-hidden="true">&times;</span>
    </button>
 </div>
}

handleSearchReset 函数按预期工作并设置状态。 filterSearchfilterSearchQuery 值都设置正确。但是,在重新渲染后,filterSearchQuery 值仍然在输入字段中可见。我该如何克服这个或我错过了什么?

提前致谢。

【问题讨论】:

    标签: javascript reactjs input


    【解决方案1】:

    由于您使用的是受控组件,仅setting them to null 不足以执行清除操作。相反,将它们设置为空字符串""。这是一个最小的完整示例:

    class Foo extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          filterSearchQuery: "",
          filterSearch: ""
        };
    
        this.handleSearchInput = this.handleSearchInput.bind(this);
        this.handleSearchReset = this.handleSearchReset.bind(this);
      }
    
      handleSearchInput(e) {
        if (e.keyCode === 13) {
          const {filterSearchQuery} = this.state;
          this.setState({
            filterSearchQuery: "",
            filterSearch: filterSearchQuery,
          });
        }
        else {
          this.setState({
            filterSearchQuery: e.target.value
          });
        }
      }
    
      handleSearchReset(e) {
        this.setState({
          filterSearchQuery: "",
          filterSearch: ""
        });
      }
    
      render() {
        const {filterSearchQuery, filterSearch} = this.state;
        return (
          <div>
            <input 
              value={filterSearchQuery} 
              onKeyUp={this.handleSearchInput} 
              onChange={this.handleSearchInput} 
            />
            {filterSearchQuery &&
              <div>
                <button onClick={this.handleSearchReset}>
                  <span>&times;</span>
                </button>
              </div>
            }
            {filterSearch &&
              <div>
                ...testing search for '{filterSearch}'...
              </div>
            }
          </div>
        );
      }
    }
    
    ReactDOM.render(<Foo />, document.getElementById("root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

    小记:

    • 由于您已经在构造函数中将this 绑定到this.handleSearchFoo,因此无需在render() 中使用箭头函数包装器。
    • 最好在所有条件句周围使用大括号以提高可读性并避免细微的错误。
    • 使用destructuring 有助于消除冗长。
    • 避免使用长水平线以提高可读性。
    • 线

      (this.state.filterSearchQuery && this.state.filterSearchQuery.length > 0) &&
      

      等价于

      this.state.filterSearchQuery &&
      

      (如果它是真实的,我们知道它已经定义并且长度 > 0)。

    【讨论】:

    • 非常感谢,我花了这么多时间。
    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 2021-05-07
    • 1970-01-01
    • 2018-12-30
    • 2012-12-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多