reactjs - 如何将react-autosuggest内部的值传递给父组件?

标签 reactjs

在我的 app.js 中,我有这个

render() {
  return (
    <div id="App">
      <SearchBar />
    </div>
  );
}

在SearchBar内部,我导入react-autosuggest并得到这个-

render() {
  const { value, suggestions } = this.state;
  const inputProps = {
    placeholder: "Search",
    value,
    onChange: this.onChange
  };

  return (
    <Autosuggest 
      style={style}
      suggestions={suggestions}
      onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
      onSuggestionsClearRequested={this.onSuggestionsClearRequested}
      getSuggestionValue={getSuggestionValue}
      renderSuggestion={renderSuggestion}
      inputProps={inputProps}
      onSubmit={this.doSomething}
      />
  );
}

所有这些函数都是react-autosuggest使用的标准样板函数。如何访问在其父级 app.js 内的 SearchBar 内搜索的内容?

最佳答案

您可以使用 props 将 Autosuggest 事件中的数据提升到父组件。在 App 内创建一个方法,并将其作为 prop 传递给 SearchBar 组件。然后,使用 Autosuggest 事件调用它。

应用程序

class App extends React.Component {
  onSubmit(e) {
    // `e` is the data that was passed through from the `Autosuggest` event.
    console.log(e);
  }

  render() {
    return (
      <div id="App">
        <SearchBar onSubmit={this.onSubmit} />
      </div>
    );
  }
}

搜索栏

<Autosuggest onClick={this.props.onSubmit} />

关于reactjs - 如何将react-autosuggest内部的值传递给父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46165097/

相关文章:

jquery - 在 React 组件中应用 sass css 时遇到问题

reactjs - 在 formik 组件之外处理 formik 表单

javascript - 使用 iFrame 表单后 iPhone 数字键盘不断弹出 (iOS Safari)

reactjs - 浏览器历史记录需要 DOM

reactjs - 在 React/Redux 应用程序中存储 RTCPeerConnection 对象的最佳位置在哪里?

reactjs - 实现 Redux 后基本 React 测试失败

javascript - 如何循环遍历数据并将值分配给 react 中的状态数组

reactjs - React.memo 不是 16.13.0 中的函数

reactjs - 来自 dnd-kit 的监听器正在干扰输入 :checkbox's onChange event

reactjs - 如何在 Material ui 中显示比文本字段宽度长的文本?