gpt4 book ai didi

javascript - 如何将子组件的状态传递给父组件?

转载 作者:行者123 更新时间:2023-11-30 19:08:37 24 4
gpt4 key购买 nike

我是 ReactJS 的新手。这么简单还请见谅。

我正在尝试将单选按钮组件 (RadioButton.js) 注入(inject)主页。这样单选按钮就会出现在主页上。它像个 child 。从RadioButton.js可以看出,我有两个单选按钮。它们的值为 buttonOnebuttonTwo .

我想要实现的是当buttonOne被选中,我想显示 <TablePage/>成分。否则,<StickyHeadTable />

RadioButton.js

export default function FormControlLabelPosition() {
const [value, setValue] = React.useState("female");

const handleChange = event => {
setValue(event.target.value);
};

return (
<FormControl component="fieldset">
<RadioGroup
aria-label="position"
name="position"
value={value}
onChange={handleChange}
row
>
<FormControlLabel
value="buttonOne"
control={<Radio color="primary" />}
label="F1"
/>
<FormControlLabel
value="buttonTwo"
control={<Radio color="primary" />}
label="F2"
/>
</RadioGroup>
</FormControl>
);
}

RadioButton被注入(inject)主页。我如何从 RadioButton.js 中获取值.这样我就可以使用条件了。

HomePage.js

  return (
<div className="home-page">
<RadioButton values={values} handleChange={handleChange}></RadioButton>
{values.flight === "buttonOne" ? <TablePage /> : <StickyHeadTable />}
</div>
);

最佳答案

单选按钮.js

export default function FormControlLabelPosition(props) {

return (
<FormControl component="fieldset">
<RadioGroup
aria-label="position"
name="position"
value={props.value}
onChange={props.handleChange}
row
>
<FormControlLabel
value="buttonOne"
control={<Radio color="primary" />}
label="F1"
/>
<FormControlLabel
value="buttonTwo"
control={<Radio color="primary" />}
label="F2"
/>
</RadioGroup>
</FormControl>
);
}

主页.js

const [value, setValue] = React.useState("female");

const handleChange = event => {
setValue(event.target.value);
};
return (
<div className="home-page">
<RadioButton values={values} handleChange={handleChange}></RadioButton>
{values.flight === "buttonOne" ? <TablePage /> : <StickyHeadTable />}
</div>
);

关于javascript - 如何将子组件的状态传递给父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58731037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com