【问题标题】:On Change event inside Typeahead is not workingTypeahead 中的 On Change 事件不起作用
【发布时间】:2021-05-31 02:21:30
【问题描述】:

我正在尝试检查 typeahead 中的 Onchange 事件是否正常工作,但显然不是。代码如下:

class Search extends Component {
 state = {
      searchName: ''
}

handleNameChange(event) {
    this.setState({searchName: event.target.value})
    console.log('Name Change: ', event.target.value);
}

render() {
    return (
      <div class="form-group">
                    <Typeahead
                        id="basic-example"
                        options={this.state.hcpName}
                        placeholder="Search by Name..."
                        onChange={this.handleNameChange}
                    />
                </div>
)}
 }

这段代码有什么问题?当我在该字段中输入时,我在控制台中看不到任何内容。

【问题讨论】:

  • 为handleNameChange尝试箭头函数
  • 试过了,没用。像这样写:handleNameChange = (event) => { this.setState({searchName: event.target.value}) console.log('Name Change: ', event.target.value); }
  • 您是否遇到任何错误?你用的是哪个版本?
  • 不,我没有收到任何错误。
  • 但是 onChange 是 Typehead 组件的属性,因为 onChange 用于输入标签,所以在你的 Type head 组件中存在一些错误

标签: javascript reactjs react-bootstrap-typeahead


【解决方案1】:

我找到了一种直接更改状态而不是调用函数的方法。方法如下:

class Search extends Component {
state = {
  searchName: ''
}


 render() {
return (
  <div class="form-group">
                <Typeahead
                    id="basic-example"
                    options={this.state.hcpName}
                    placeholder="Search by Name..."
                    onInputChange={(searchName) => this.setState({searchName})}
                />
            </div>
    )}
  }

基本上,我使用 onInputChange 而不是 onChange,然后直接在 typeahead 内部更改状态。

【讨论】:

猜你喜欢
  • 2013-06-04
  • 2016-06-04
  • 1970-01-01
  • 2018-10-11
  • 2013-01-25
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 2021-02-23
相关资源
最近更新 更多