如何从react-bootstrap-typeahead中的下拉列表中获取当前选定的值?

问题描述 投票:1回答:1

我想在我的申请中使用react-bootstrap-typeahead。我在这里使用示例https://ericgio.github.io/react-bootstrap-typeahead/。这是组件

<Typeahead
 labelKey={(option) => `${option.firstName} ${option.lastName}`}
 options={[
 {firstName: 'Art', lastName: 'Blakey'},
 {firstName: 'John', lastName: 'Coltrane'},
 {firstName: 'Miles', lastName: 'Davis'},
 {firstName: 'Herbie', lastName: 'Hancock'},
 {firstName: 'Charlie', lastName: 'Parker'},
 {firstName: 'Tony', lastName: 'Williams'},
 ]}

 onInputChange={this.handleInputChange}
 onKeyDown={ this._handleChange}
 value={this.state.value}
 placeholder="Who's the coolest cat?"
/>

这是handlechange功能

_handleChange = (e) => {
  console.log("value",e.target.value)
}

当我尝试控制日志选择值时,它显示以前选择的值。我想获得当前选定的值。如何获取当前选定的值。

reactjs autocomplete
1个回答
1
投票

它似乎是预期的行为,因为onKeyDown事件在输入改变之前触发,因此event.target.value返回先前的值。要返回所选值,请使用

  • onChange - 当输入值改变时调用(和)
  • onInputChange - 在输入值更改时调用。接收输入的字符串值以及原始事件。

相反的事件。

class Example extends React.Component {
  state = {};

  handleInputChange(input, e) {
    console.log("value", input)
  }

  handleChange(selectedOptions) {
    console.log(selectedOptions);
  }

  render() {
    return (
      <Typeahead
        id="typeahead"
        labelKey={option => `${option.firstName} ${option.lastName}`}
        options={[
          { id: 1, firstName: "Art", lastName: "Blakey" },
          { id: 2, firstName: "John", lastName: "Coltrane" },
          { id: 3, firstName: "Miles", lastName: "Davis" },
          { id: 4, firstName: "Herbie", lastName: "Hancock" },
          { id: 5, firstName: "Charlie", lastName: "Parker" },
          { id: 6, firstName: "Tony", lastName: "Williams" }
        ]}
        placeholder="Who's the coolest cat?"
        onInputChange={this.handleInputChange}
        onChange={this.handleChange}
      />
    );
  }
}

Demo

© www.soinside.com 2019 - 2024. All rights reserved.