Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
964 views
in Technique[技术] by (71.8m points)

react 嵌套路由中, 在父组件中给children添加参数, 子组件为什么接收不到

浏览器访问子组件路由/parent/child, 子组件为什么接收不到参数

父组件A
路由 /parent
parent.js

const Parent = props => {
  const { children } = props;
  const childrenWithProps = React.Children.map(children, child => React.cloneElement(child, { a: 123 })

  console.log('childrenWithProps', childrenWithProps)
  // 在这里输出 childrenWithProps 中是有参数a的

  return (
      <div>
        {childrenWithProps}
      </div>
  );
};

export default Parent;

子组件B
路由 /parent/child
child.js

import React from 'react';

const Child = (props) => {

  console.log('Child', props, props.a)
  // 这里输出props, 为什么props 里会没有属性a?

  return (
    <div>child</div>
  )
}

export default Child;

路由文件
router.js

 {
    path: '/parent',
    component: './Parent',
    routes: [
      {
        path: '/parent/child',
        component: './Parent/Child',
      },
     ]
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

已解决, 父组件少clone了一次.
parent.js

const Parent = props => {
  const { children } = props;
  
  // 1. 遍历children内层的组件 -> children.props.children , 克隆每个组件并添加上新的属性, 返回新的children.props.children
  const deepChildrenWithProps = React.Children.map(children.props.children, child => React.cloneElement(child, { a: 1 }));

  // 2. 用新的children.props.children 覆盖 chilren 里现有的 children.props.children
  const childrenWithProps = React.cloneElement(children, { children: deepChildrenWithProps });

  return (
      <div>
        {childrenWithProps}
      </div>
  );
};

export default Parent;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...