【问题标题】:Search functionality no longer working after converting from React class to function component从 React 类转换为函数组件后,搜索功能不再起作用
【发布时间】:2020-06-10 21:52:34
【问题描述】:

this question 的帮助下,我已将 React 类组件转换为函数组件。

除此按钮外,一切正常:

{/* 
            Show only if user has typed in search.
            To reset the input field, we pass an 
            empty value to the filterUpdate method
          */}
{hasSearch && <button onClick={filterUpdate}>Clear Search</button>}

当我点击它时,我会在搜索框中看到[object Object]。我也试过了:

{hasSearch && <button onClick={filterUpdate("")}>Clear Search</button>}

但这会使搜索功能停止工作。 这是旧的(类组件)代码(正在工作)。

 {hasSearch && (
            <button onClick={this.filterUpdate.bind(this, "")}>
              Clear Search
            </button>
          )}

所有代码都在另一个问题中。不过,这提供了上下文。

 // update filterText in state when user types
  const filterUpdate = (value) => {
    setfilterText(value);
  };


/* ###################### */
/* ##### Search bar ##### */
/* ###################### */

// need a component class here
// since we are using `refs`
class Search extends Component {
  render() {
    const { filterVal, filterUpdate } = this.props;
    return (
      <form>
        <input
          type="text"
          ref="filterInput"
          placeholder="Type to filter.."
          // binding the input value to state
          value={filterVal}
          onChange={() => {
            filterUpdate(this.refs.filterInput.value);
          }}
        />
      </form>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    首先你需要这样做:

    <button onClick={() => filterUpdate("")}> Clear Search</button>
    

    这将停止立即调用它

    【讨论】:

    • 解决了,谢谢。当系统允许时我会接受:)
    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2021-05-29
    相关资源
    最近更新 更多