【问题标题】:How to get current selected value from dropdown in react-bootstrap-typeahead?如何从 react-bootstrap-typeahead 的下拉列表中获取当前选定的值?
【发布时间】:2019-08-13 15:05:49
【问题描述】:

我正在尝试在我的应用程序中使用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)
}

当我尝试控制台记录选择的值时,它会显示以前选择的值。 我想获取当前选定的值。如何获取当前选定的值。

【问题讨论】:

  • 不确定,这会解决它,但不是因为,您没有使用 onKeyDown onKeyDown={() =&gt; this._handleChange} 执行函数
  • 不,它不起作用

标签: reactjs autocomplete


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多