在不扩展 class / 功能的情况下反应访问自道具

React accessing self props without extending class / function

我正在 React Native 中构建自定义组件,它将自动管理作为 children 传递的组件。

此组件还将向 children 添加自定义道具。

但是需要注意的是 children 组件无法直接使用这些道具;相反,为了访问这些孩子的 props object,创建 SFC 或扩展 React.Component 是必要的。

我想知道是否有一种方法可以在不这样做的情况下访问这些添加的道具?

例如,在下面的代码中,我希望能够像这样访问 managerProp

<ManagerComponent>
  <Child onPress={ managerProp.handleOnPress }>
    {managerProp.something}
  </Child>
</ManagerComponent>

执行此操作的方法是让您的 ManagerComponent 公开一个渲染道具(基本上是一个它将调用以渲染其子项的函数)。它可以将其 "extra" 属性传递给此函数。您可以使用 children 作为 render 道具,这会导致类似:

function ManagerComponent({children}) {
   const extraProps = {handleOnPress: ..., ...}
   // The trick is we call children as a function instead
   // of treating it as a component to render
   return <div>{children(extraProps)}</div>
}

ManagerComponent.propTypes = { children: PropTypes.func.isRequired }

function Foo() {
  return (
     <ManagerComponent>
        {managerProps => (
          <Child onPress={managerProps.handleOnPress}>
             {managerProps.something}
          </Child>)
        }
     </ManagerComponent>
  )
}

这里 blog article(不是我的)更详细地讨论了这个概念。