父子组件Props传递的方法有哪些

78 阅读1分钟

父子组件Props传递的方法

在父组件中如何给子组件添加props的方法

  1. 组件上直接传参<Wrap><Content configKey={} /></Wrap>
  2. 在父组件中获取child子组件,然后给子组件添加额外的props
// 父组件
function Wrap(){
  const props = {configKey: 'extraKey'};
  const ChildrenWithProps = getChildrenWithProps(child,props);
  return (<div>{ChildrenWithProps}<div/>)
}

// 子组件
function Content({
  configKey, // 父组件没有传递,但是子组件有该props
  otherAttributes
}){}

// 使用
<Wrap><Content otherAttributes={} /></Wrap>
// 子组件
export const Content = ({
  content, // 思考:content属性组件没有传props,哪里来的
  configKey, // 思考:tabKey属性组件上没有传props,哪里来的
  services = [],
  constants = {},
}) => {
//...
}

案例

import React from 'react';
// 在父组件中给child新增props
export const getChildrenWithProps = (children, props) => {
  return React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { ...child.props, ...props });
    }
    return child;
  });
};

// 父组件
function Wrap({children}) {
  // mock data
  const config = [{key:'dev', title:'test'}];
  return (<Div>
    {config.map((item) => {
      const key = item.key;
      // 给子组件添加额外的props; the key to code
      const childrenWithProps = getChildrenWithProps(children, {
        content: {extraProps:'content'},
        configKey: key,
      });
      return (
        <Div><span>{item.title}</span>
         {childrenWithProps}
        </Div>);
    })}
   </Div>);
}