使用React-Bootstrap-Typehead的问题

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

我正在使用react-bootstrap-typehead构建类型头,并遇到TypeError。

详细信息:我可以在字段中成功键入内容,过滤选项并使用菜单,但是,选择选项后,页面将变为空白并显示此错误:

“ TypeError:无法读取未定义的属性'onChangeState'”

  160 | <Typeahead
  161 |   id="basic-typeahead-example"
  162 |   labelKey="state"
> 163 |   onChange={(e) => this.onChangeState(e)}
      | ^  164 |   options={[
  165 |     { state: 'AL' },
  166 |     { state: 'AK' },

Typehead:

function StateInput() {

  const [selected, setSelected] = useState([]);

  return (
    <>
      <Typeahead
        id="basic-typeahead-example"
        labelKey="state"
        onChange={(e) => this.onChangeState(e)}
        options={[
          { state: 'AL' },
          { state: 'AK' },
          { state: 'AZ' },
          { state: 'AR' },
          { state: 'CA' }
        ]}
        placeholder="Choose a state..."
        selected={selected}
        value={setSelected}
      />
    </>
  )
}

onChange函数:

  onChangeState(e) {
    this.setState({
      state: e.target.value
    })
  }
javascript reactjs forms react-bootstrap react-bootstrap-typeahead
1个回答
0
投票

据我所知,有几个问题。

  1. [我不确定您相对于onChangeState定义StateInput的位置,但是由于this绑定不正确,因此未定义,因此发生了错误。如果该方法来自父组件,则应将其作为prop(props.onChangeState)传递。
  2. 预先输入传递给onChange的参数实际上是an array of selections,不是事件。
  3. React Bootstrap Typeahead不接受value道具,因此setSelected在那儿什么也没做。

以下应该起作用:

const StateInput = (props) => {
  const [selected, setSelected] = useState([]);

  return (
    <Typeahead
      id="basic-typeahead-example"
      labelKey="state"
      onChange={setSelected}
      options={[
        { state: 'AL' },
        { state: 'AK' },
        { state: 'AZ' },
        { state: 'AR' },
        { state: 'CA' }
      ]}
      placeholder="Choose a state..."
      selected={selected}
    />
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.