【发布时间】:2021-07-19 23:24:58
【问题描述】:
我正在尝试在我的应用程序中使用 react-select“选择”组件作为一种方便的方式来生成一系列下拉列表作为我的 UI 的一部分。
从 react-select 文档中,我已经能够让这些组件使用所需的选项进行渲染;但是,从 Select 组件中存储的值通过 useState 挂钩存储为状态变量。
我需要将这些菜单的值(状态)传递给父组件。我不知道如何让这些函数中生成的状态值能够在更高的父组件中读取。以下是我目前拥有的一些 sn-ps。
注意:为这些子函数填充选项道具的数组是在更高的父组件处生成的,并作为道具传递下来。部分代码似乎没有问题
function ButtonA(props){
const options=props.buttonAOptions;
const [selectedOption, setSelectedOption]=useState(null);
return(
<div>
<p>Button A
<Select
value={selectedOption}
onChange={newValue =>setSelectedOption(newValue)}
options={options}
/>
</p>
</div>
)
}
function ButtonB(props){
const options=props.buttonBOptions;
const [selectedOption, setSelectedOption]=useState(null);
return(
<div>
<p>Button B
<Select
value={selectedOption}
onChange={newValue =>setSelectedOption(newValue)}
options={options}
/>
</p>
</div>
)
}
class Window extends React.Component {
constructor(props){
super(props);
}
// there are some other methods in here that are not related to this problem
render(){
return (
<div>
<ButtonA
buttonAOptions={this.props.buttonAOptions}
/>
<ButtonB
buttonBOptions={this.props.buttonBOption}
/>
</div>
)
}
}
【问题讨论】:
-
我从这里开始。在这种情况下,这似乎不是一个选项,因为 react-select 组件需要 setState。我知道 Redux 有一个映射状态到道具功能,但我不知道在这个例子中提升状态有什么帮助
标签: reactjs react-select