admin管理员组文章数量:1431726
In my React child ponent I have access to a variable options
which returns an array of objects.
In this ponent I have a function which checks if there are options:
const hasOptions = () => options.length > 0;
console.log(hasOptions());
This returns true
or false
.
In my parent ponent I need this boolean value to conditionally add some styling (based on the boolean value).
How do I pass this boolean value from my child to parent ponent?
In my React child ponent I have access to a variable options
which returns an array of objects.
In this ponent I have a function which checks if there are options:
const hasOptions = () => options.length > 0;
console.log(hasOptions());
This returns true
or false
.
In my parent ponent I need this boolean value to conditionally add some styling (based on the boolean value).
How do I pass this boolean value from my child to parent ponent?
Share Improve this question asked Aug 31, 2021 at 8:50 meezmeez 4,82810 gold badges56 silver badges123 bronze badges 1- Does this answer your question? How to pass data from child ponent to its parent in ReactJS? – Anwer AR Commented Aug 31, 2021 at 9:02
3 Answers
Reset to default 2You can create a state variable in the parent ponent, and then pass the setXXX
method to the child ponent, in the child ponent call the setXXX
method to pass the boolean variable to the parent.
In general you should not do that. React is based on the idea of one directional data flow. Data flows down, from parent to children and events vice versa. So the correct solution would be to lift state to parent ponent and pass it to the children. But if you absolutely need to do it, you can pass callback to child.
function Parent() {
const [hasOptions, setHasOptions] = useState(false);
return <Child setHasOptions={setHasOptions} />
}
function Child({ setHasOptions }) {
useEffect(() => {
setHasOptions(hasOptions())
}, [options.length, setHasOptions ]);
// ...
}
If possible, give the parent access to options
and have it provide hasOptions
to the child, rather than doing it the other way around. State should be "lifted up" the ponent hierarchy (from children to parents) when possible.
If it's not possible, you'll have to have the parent provide a function to the child (as a prop) that it can then use to tell the parent whether it has options. This is more plicated and can lead to unnecessary rendering (for example, the parent rendering the child without the additional styling, the child calling the parent back, and the parent having to re-render with the additional styling).
本文标签: javascriptHow do I pass a boolean value from my React child to parent componentStack Overflow
版权声明:本文标题:javascript - How do I pass a boolean value from my React child to parent component - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745450855a2658876.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论