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

vid*_*idy 5 autocomplete reactjs

我正在尝试在我的应用程序中使用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?"
/>
Run Code Online (Sandbox Code Playgroud)

这是句柄更改函数

_handleChange = (e) => {
  console.log("value",e.target.value)
}
Run Code Online (Sandbox Code Playgroud)

当我尝试控制台记录选择的值时,它显示以前选择的值。我想获取当前选择的值。我怎样才能获得当前选择的值。

Vad*_*hev 5

这似乎是预期的行为,因为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}
      />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

演示