我正在使用react-select
来允许用户从给定的FEATURE列表中进行多次选择。我的Typescript代码看起来像这样
`
import React from "react";
import { Select } from "react-select";
import { FEATURE } from "routes/models/constants";
interface FeatureSelectProps {
SelectedOption ?: string;
}
export default class FeatureSelect extends React.Component<FeatureSelectProps, any> {
handlechange(SelectedOption: any)
{
this.setState({SelectedOption});
if(SelectedOption)
{
console.log(`Selected: ${SelectedOption.label}`);
}
}
render() {
const { SelectedOption = ' ' } = this.state;
return (
<Select multi={true}
name="Features"
placeholder="+ Add Feature"
options={FEATURE}
value={SelectedOption}
onChange={this.handlechange} />
);
}
}
`
在加载页面时显示此错误:Uncaught TypeError: Cannot read property 'SelectedOption' of null
同样的原因是什么以及如何解决这个问题?
答案 0 :(得分:0)
通过以下编辑解决了上述问题: `
export default class FeatureSelect extends React.Component<any, any> {
state = {
selectedOption: ""
};
handleChange = (selectedOption: any) => {
this.setState({ selectedOption });
if (selectedOption) {
console.log(`Selected: ${selectedOption.label}`);
}
};
render() {
const { selectedOption } = this.state;
return (
<Select
placeholder="Select Feature(s)"
multi={true}
value={selectedOption}
onChange={this.handleChange}
options={FEATURE}
/>
);
}
}
`