简体   繁体   中英

How to get current selected value from dropdown in react-bootstrap-typeahead?

I am trying to use react-bootstrap-typeahead in my appliccation. I am using example shown here https://ericgio.github.io/react-bootstrap-typeahead/ . this is component

<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?"
/>

this is handlechange function

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

when i try to console log selcted value it shows previously selected value. I want to get current selected value. How can I get current selected value.

It appears to be expected behavior since onKeyDown event triggers before the input is changed and thus event.target.value returns previous value. To return selected value use

  • onChange - invoked when the input value changes and(or)
  • onInputChange - invoked when the input value changes. Receives the string value of the input, as well as the original event.

events instead.

Example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM