嗨,我正在尝试在我的react应用程序中实现选择框。我正在使用https://www.npmjs.com/package/react-select中的npm。下面是我的代码。
const options = [
{ value: 'Current', label: 'Current' },
{ value: 'Future', label: 'Future' },
{ value: 'Closed', label: 'Closed' },
];
export class EditParametersPanelComponent extends React.Component {
this.state = {
selectedOption: null,
}
handleChange(selectedOption) {
this.setState({ selectedOption });
console.log('Option selected:', selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<Select
instanceId="storeFilter"
value={selectedOption}
onChange={this.handleChange}
options={options}
placeholder="Store"
/>,
);
}
}
我能够在网页中呈现选择框。每当我单击任何一个选项时,都会遇到错误。
1. Uncaught TypeError: this.setState is not a function
2. Warning: Failed prop type: You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.
有人可以帮助我确定并解决此错误吗?任何帮助将不胜感激。谢谢
答案 0 :(得分:1)
您必须使用箭头功能进行绑定
handleChange = selectedOption => {
this.setState({ selectedOption });
console.log('Option selected:', selectedOption);
}
或者您可以在下面使用其他方式
<Select
instanceId="storeFilter"
value={selectedOption}
onChange={this.handleChange.bind(this)}
options={options}
placeholder="Store"
/>,