我正在尝试取消选中复选框并将其重置为默认值后禁用选择列表。但是我看到了我选择的一个。我正在使用React-select作为选择和选项。
APP.js
const adultOptions = [{ value: '1', label: '1' },{ value: '2', label: '2' }];
class App extends Component {
state = {
disableSelect2: true
}
selectDisableHandler2 = () => {
const showSelect = this.state.disableSelect2;
this.setState({ disableSelect2: !showSelect });
}
render() {
return (
<>
<div className="Container">
<div>
<table style={{ borderStyle: "solid" }}>
<caption style={{ borderStyle: "inherit" }}>
<input type="checkbox"
onClick={this.selectDisableHandler2} />Room 2</caption>
<tbody>
<tr>
<th>Adult (18+)</th>
<th>Children (0-17)</th>
</tr>
<tr>
<td>
<Select
options={adultOptions}
isDisabled={this.state.disableSelect2}
defaultValue={this.state.disableSelect2 ? adultOptions[0] : null}/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</>
);
}
}
export default App;
```[In the image after unchecking checkbox, the options value is set to "2" which I selected, but I wanted it to be default value i.e. "1" ][1]
[1]: https://i.stack.imgur.com/S5gjP.png
答案 0 :(得分:0)
您需要在组件状态下处理选择的值:
<Select
value={this.state.selectedOption}
isDisabled={this.state.disableSelect2}
options={adultOptions}
onChange={this.handleChange}
/>
让复选框处理程序对其进行相应更新:
selectDisableHandler2 = () => {
const showSelect = this.state.disableSelect2;
this.setState({
disableSelect2: !showSelect,
selectedOption:
showSelect === true ? this.state.selectedOption : adultOptions[0]
});
};
代码和框: