如何在React中将道具道具从Parent传递给this.props.children



我很难将道具传递给this.props.children。我知道有一些类似的帖子,然而,我相信我已经尝试了大多数公认的解决方案,但它仍然没有表现出来,也没有达到预期。所以,我想我错过了一些重要的东西。

总的想法是:我有一个<NavBar>组件,我想把它包装在我的页面上,如下所示。我希望包装后的页面接受从<NavBar>组件传递下来的道具。

<NavBar>
<Container>
<Grid container>
<Grid item>
...
</Grid>
</Grid>
</Container>
</NavBar>

目前我的<NavBar>定义如下:

class NavBar extends React.Component<React.PropsWithChildren<NavBarProps>, NavBarState>

所以,我的组件有一个道具children?: React.ReactNode。在我的render()方法中,我渲染了一个<AppBar>(来自Material UI库(,在它下面我显示类似的children

render() {
const {children} = this.props;
return(
<>
<AppBar>...</AppBar>
{children}
</>
)
}

我做过的一些尝试

render() {
const children = React.cloneElement(this.props.children as React.ReactElement, {
test: "test"
});
return(
<>
<AppBar>...</AppBar>
{children}
</>
)
}

我的期望:在这种情况下,我希望能够从<NavBar>中包装的任何页面访问test道具,如this.props.test

我也试过

const children = React.Children.map(this.props.children as React.ReactElement, (child) =>
React.cloneElement(child, { test: "test" })
);

&

const children = React.Children.map<ReactNode, ReactNode>(this.props.children, (child) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, { test: "test" });
}
});

到目前为止的结果:我没有成功,尝试从我的页面访问this.props.test返回undefined

我认为您的第三次尝试没有任何问题。下面是一个使用该方法的工作示例。请注意,与第二次尝试不同,您确实需要从map中选择return

function Test() {
return (
<Parent>
<Child />
</Parent>
);
}
class Parent extends React.Component {
render() {
const children = React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, {test: 'test'});
});
return (
<div>
<h3>Parent</h3>
{children}
</div>
);
}
}
class Child extends React.Component {
render() {
return (
<div>
<h3>Child</h3>
Test Prop: {this.props.test}
</div>
);
}
}
ReactDOM.render(<Test/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

最新更新