我正在使用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
})
}
据我所知,有几个问题。
onChangeState
定义StateInput
的位置,但是由于this
绑定不正确,因此未定义,因此发生了错误。如果该方法来自父组件,则应将其作为prop(props.onChangeState
)传递。onChange
的参数实际上是an array of selections,不是事件。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}
/>
);
};