【问题标题】:Issue with using React-Bootstrap-Typehead使用 React-Bootstrap-Typeahead 的问题
【发布时间】:2020-03-05 12:00:31
【问题描述】:

我正在使用 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' },

字头:

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】:

    据我所知,有几个问题。

    1. 我不确定你在哪里定义了onChangeState 相对于StateInput,但发生错误是因为this 未正确绑定,因此未定义。如果方法来自父组件,则应将其作为道具 (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}
        />
      );
    };
    

    【讨论】:

      【解决方案2】:

      我找到了您的帖子,因为我试图在 onChange 上实现获取数据,并将值作为获取数据的查询(选项,在 Typeahead 中)。对于这种情况,AsyncTypeahead 更适合我的情况,onSearch 与典型的onChange 具有相同的行为。

      在此处查看更多信息:http://ericgio.github.io/react-bootstrap-typeahead/#asynchronous-searching

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-20
        • 2012-11-18
        • 1970-01-01
        • 2013-08-12
        • 1970-01-01
        • 2013-08-06
        相关资源
        最近更新 更多