将 props 传递给父组件,它也作为 React.js 中的 prop 传递

时间:2021-02-18 16:32:50

标签: reactjs react-hooks react-props react-functional-component

我有三个嵌套组件,如下图所示。

example structure

component B 可以容纳不同类型的组件(图中的 C1、C2、C3)。因此,component C(孙组件)作为道具传递给 component B 并在其中呈现。这是一个小例子:

组件 A

return (
   <compontentB 
      content={<compontentC1 setIsC1Valid={(isValid) => {console.log(isValid)}}/>}
   />
   <compontentB 
      content={<compontentC2 setIsC2Valid={(isValid) => {console.log(isValid)}}/>}
   />
   <compontentB 
      content={<compontentC3 setIsC3Valid={(isValid) => {console.log(isValid)}}/>}
   />
)

组件 B

// use isValid of component C here in this component
return (
   <div> {props.content} </div>
)

在每个 component C 内,我有一个布尔状态,并希望在 component B 内更改时使用该值。为此,我必须将 component C 内的值传递给其直接父级 (component B)。

问题是 component C 已经作为 prop 传递,所以我只能通过回调函数侧的 prop 将值发送到 component A,但不能直接太 component B

组件 C

const [isValid, setIsValid] = useState(false);

useEffect(() => {
   //send isValid to component B
   props.setIsCValid(isValid);
}, [isValid]);

return (
   <button onclick={() => setIsValid(!isValid)}/>
)

有没有办法将 Component C 的状态值直接发送到 Component B? 我使用函数式组件和 React 钩子。

我希望我以合理易懂的方式描述了问题,并且示例不要太抽象。

0 个答案:

没有答案