通过多个下拉菜单设置所选值的状态

时间:2018-10-21 06:15:31

标签: reactjs

我有一个父级<FirstStep />组件,其中包含两个下拉菜单组件。 我需要设置所选值的state

如果我只有一个下拉菜单,那么该代码可以正常工作,但是我有两个下拉菜单,因此我不能只传递onChange,因为每个下拉菜单都需要一个onChange

<FirstStep />组件:

const items = [
    { name: 'aa', value: 1 },
    { name: 'bb', value: 2 },
    { name: 'cc', value: 3 },
];

export default ({ active, onChange, selection }) => (
    <Card active={active}>
        <CardHeader text="Please choose" >
            <Circle active small text="1" />
        </CardHeader>
        <Dropdown items={items} placeholder="Please choose" onChange={onChange} selection={selection}/> 
        <Dropdown items={[{ name: "dd", value: 1 }]} selection="Please choose" />
    </Card>
);

还有<FirstStep />的故事:

storiesOf('FirstStep', module)
    .add('default', () => (
        <StateContainer state={{ selected: '' }}>
            {({ state, setState }) => (
                <FirstStep onChange={selection => setState({ selected: selection.name })}
                    selection={state.selected} />
            )}
        </StateContainer>
    ));

如果组件中有一些下拉菜单,请告知如何设置所选值的state

1 个答案:

答案 0 :(得分:0)

您可以在第二个Dropdown中将第二个onChange传递给FirstStep,或使用相同的onChange函数并传递一个标识符或类似的东西。

或者如果两个下拉菜单都打算在状态(本例中为state)中修改相同的值,则只需将相同的onChange设置为第二个下拉菜单即可。

<FirstStep onChange={selection => setState({ selected: selection.name })}
           onChange2={selection => setState({ selectedB: selection.name })}
           selection={state.selected} />

export default ({ active, onChange, onChange2, selection }) => (
<Card active={active}>
    <CardHeader text="Please choose" >
        <Circle active small text="1" />
    </CardHeader>
    <Dropdown items={items} placeholder="Please choose" onChange={onChange} selection={selection}/> 
    <Dropdown items={[{ name: "dd", value: 1 }]} selection="Please choose" onChange={onChange2} />
</Card>
);

<FirstStep
  selection={state.selected} 
  onChange={(ident, selection) => {
    if(ident ===1) {
      setState({selected: selection.name}) 
    } else {
      setState({selectedB: selection.name})
    }}}
/>

export default ({ active, onChange, selection }) => (
<Card active={active}>
    <CardHeader text="Please choose" >
        <Circle active small text="1" />
    </CardHeader>
    <Dropdown items={items} placeholder="Please choose" onChange={(selected) => onChange(1, selected)} selection={selection}/> 
    <Dropdown items={[{ name: "dd", value: 1 }]} selection="Please choose" onChange={(selected) => onChange(2, selected)}/>
</Card>

);

或者只是

export default ({ active, onChange, selection }) => (
<Card active={active}>
    <CardHeader text="Please choose" >
        <Circle active small text="1" />
    </CardHeader>
    <Dropdown items={items} placeholder="Please choose" onChange={onChange} selection={selection}/> 
    <Dropdown items={[{ name: "dd", value: 1 }]} selection="Please choose" onChange={onChange}/>
</Card>

);

如果它们都修改了状态。选择。

这些只是为了给您一些替代方案的想法,显然您需要根据自己的需要对它们进行调整。