React:子组件中的父组件道具无需显式传递

Mat*_*att 6 javascript reactjs

是否可以让父组件的 props 在子组件中可用而不将它们传递下来?

我正在尝试实现一个提供程序模式,以便访问其子组件中的所有提供程序道具。前任:

假设下面的提供程序 compFetchProvider 将自行获取数据和主题道具,并且当它包含任何子组件时,我也想访问子组件中的道具“数据”和“主题”。我们怎样才能实现它呢?

class FetchProvider 
{

   proptypes= {
     data: PropTypes.shape({}),
     theme: PropTypes.shape({})
   }

   render()
   {
     // do some
   }

   mapStateToProps()
   {
      return {data, theme};
   }
}

class ChildComponent
{

   proptypes= {
     name: PropTypes.shape({})
   }

   render()
   {
     const{data, them} = this.props; // is this possible here?
     // do some
   }
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用上面的组件,如下所示。

<FetchProvider>
   <ChildComponent name="some value"/>  //how can we access parent component props here? without passing them down
<FetchProvider/>
Run Code Online (Sandbox Code Playgroud)

Ray*_*Ray 0

您可以使用React.Children来迭代子元素,并使用 传递您想要发送到新克隆元素的任何道具React.cloneElement

前任:

class Parent extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { children } = this.props;
    const newChildren = React.Children.map(children, child =>
      React.cloneElement(child, { myProp: 'test' }));

    return(
      <View>
        {newChildren}
      </View>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)