Joe*_*e C 5 javascript reactjs
我有一个 Parent 组件,它充当其子组件的包装器。如何将道具传递给将使用以下格式呈现的孩子?
import React, { useEffect, useState } from 'react';
const Parent = ({ children }) => {
const [completeState, setCompleteState] = useState(false);
useEffect(
() => {
/* .. code that runs then sets completeState to true */
setCompleteState(true);
}, []
);
return (
<section>
/*
how to pass a 'didComplete' prop to children?
didComplete={completeState}
*/
{children} // Child component below would be rendered here with the didComplete prop passed in
</section>
)
}
Run Code Online (Sandbox Code Playgroud)
import React from 'react';
const Child = ({ didComplete }) => (<h1>The function completed? {didComplete}</h1>);
Run Code Online (Sandbox Code Playgroud)
Ful*_*Guy 11
这props.children是一个 React Element,它只是一个简单的 JS 对象,描述了需要在 DOM 中呈现的内容。
为了提供额外的细节,我们需要克隆现有的 React Element 对象并提供额外的细节。
为此,我们可以使用React.cloneElementAPI 将附加道具传递给children:
return (
<section>
{React.cloneElement(children, {didComplete: completeState})}
</section>
);
Run Code Online (Sandbox Code Playgroud)