我有一个父组件 Questions
和两个子组件。Question1
和 Question2
. Question1
和 Question2
都返回一个 AutoComplete component
(自 material-ui
). 的选项。Question2
应基于在 Question1
(graphql
请求使用所选的值作为输入)。) 我读了很多关于如何在同级组件之间传递值的文章,但我找不到明显的方法来实现这种情况。我只是需要一些关于如何处理这个问题的指导。
我的代码结构是这样的。
export const Questions = ({ questionLabel }: QuestionsProps) => {
return (<div>
<Question1 />
<Question2 />
</div>
)
//-
export const Question1 = () => {
const [open, setOpen] = React.useState(false);
const [options, setOptions] = React.useState([]);
return (
<Autocomplete
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
options={options}
loading={loading}
autoHighlight
onChange={
(event, value) => {
console.log(value)
}
}
//...
)
//-
export const Question2 = () => {
const [open, setOpen] = React.useState(false);
const [options, setOptions] = React.useState([]);
const { loading, data } = useQuery(query2, {
variables: { selectedFromQuestion1: *** need the value here *** }});
useEffect(() => {
if (!open) {
setOptions([]);
} else {
if (data) {
setOptions(data.info.data);
}
}
}, [open]);
}
return (
<Autocomplete
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
options={options}
loading={loading}
autoHighlight
onChange={
(event, value) => {
console.log(value)
}
}
//...
)
-