最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I pass a boolean value from my React child to parent component - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 2

You 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).

发布评论

评论列表(0)

  1. 暂无评论