我很难把道具传给别人 this.props.children
. 我知道有一些类似的帖子,但是,我相信我已经尝试了大多数被接受的解决方案,它仍然没有表现出来,也没有达到预期的效果。所以,我想我错过了一些重要的事情。
总的想法是:我有一个 <NavBar>
我希望在页面周围 Package 的组件,如下所示。我希望 Package 的页面能够接受从 <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>
(来自材质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}
</>
)
}
我的期望:在这种情况下,我希望能够访问 test
Package 在其中的任何页面的道具 <NavBar>
喜欢 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
.
1条答案
按热度按时间qlvxas9a1#
我看你的第三次尝试没有任何问题。下面是一个使用该方法的工作示例。注意,与第二次尝试不同,您确实需要
return
从map
.