如何在react中将props props从父级传递到this.props.children

c9qzyr3d  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(311)

我很难把道具传给别人 this.props.children . 我知道有一些类似的帖子,但是,我相信我已经尝试了大多数被接受的解决方案,它仍然没有表现出来,也没有达到预期的效果。所以,我想我错过了一些重要的事情。
总的想法是:我有一个 <NavBar> 我希望在页面周围 Package 的组件,如下所示。我希望 Package 的页面能够接受从 <NavBar> 组成部分。

  1. <NavBar>
  2. <Container>
  3. <Grid container>
  4. <Grid item>
  5. ...
  6. </Grid>
  7. </Grid>
  8. </Container>
  9. </NavBar>

目前我 <NavBar> 定义如下:

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

所以,我的组件有一个道具 children?: React.ReactNode . 在我的 render() 方法我正在渲染一个 <AppBar> (来自材质ui库)在其下方显示 children 与此类似:

  1. render() {
  2. const {children} = this.props;
  3. return(
  4. <>
  5. <AppBar>...</AppBar>
  6. {children}
  7. </>
  8. )
  9. }

我做过一些尝试:

  1. render() {
  2. const children = React.cloneElement(this.props.children as React.ReactElement, {
  3. test: "test"
  4. });
  5. return(
  6. <>
  7. <AppBar>...</AppBar>
  8. {children}
  9. </>
  10. )
  11. }

我的期望:在这种情况下,我希望能够访问 test Package 在其中的任何页面的道具 <NavBar> 喜欢 this.props.test 我还尝试:

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

&

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

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

qlvxas9a

qlvxas9a1#

我看你的第三次尝试没有任何问题。下面是一个使用该方法的工作示例。注意,与第二次尝试不同,您确实需要 returnmap .

  1. function Test() {
  2. return (
  3. <Parent>
  4. <Child />
  5. </Parent>
  6. );
  7. }
  8. class Parent extends React.Component {
  9. render() {
  10. const children = React.Children.map(this.props.children, (child) => {
  11. return React.cloneElement(child, {test: 'test'});
  12. });
  13. return (
  14. <div>
  15. <h3>Parent</h3>
  16. {children}
  17. </div>
  18. );
  19. }
  20. }
  21. class Child extends React.Component {
  22. render() {
  23. return (
  24. <div>
  25. <h3>Child</h3>
  26. Test Prop: {this.props.test}
  27. </div>
  28. );
  29. }
  30. }
  31. ReactDOM.render(<Test/>, document.getElementById('root'));
  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
  2. <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
  3. <div id="root"/>
展开查看全部

相关问题