使用 Context API 与 CloneElement 传递直接后代的道具

Use of Context API vs CloneElement for passing down props for direct descendent

所以,我有两个组件,一个始终是另一个的直系后代。我想将道具从 parent 组件传递到 child。可能有多个 child 组件。有两种方法可以实现。

React.Children.map(children, (child) =>
  React.cloneElement(child, { someProp: 'value' })
)

或使用上下文 API

<Context.Provider value={{ someProp: 'value' }}>
  {this.props.children}
</Context.Provider>

两者都会产生相同的 DOM 结构,但是,上下文 API 的代码稍微多一些,并且会产生更多的 React 组件。

那么哪个更注重性能,值得推荐。我找不到任何与此比较相关的讨论,因此在这里提问。

新的 Context API 非常有趣,可以帮助我们处理 prop-drilling 并使 render props 模式的使用更加清晰,但由于不必要的重新渲染,它带来了一些“性能问题” .事实上,这不是问题,因为 API 提供了一种方法来处理这种不必要的重新渲染。 see link if this helpsoptimizing-performance-in-context api

上下文 API 的使用对于将数据传递给直接后代来说似乎有点矫枉过正。

如果 child 知道数据将从 parent 传递(这是通过使用 <Context.Consumer> 推测的),它可以直接使用 render prop 模式,例如:

<Parent>{passedProps => <Child {...passedProps}/>}</Parent>

{children({ someProp: 'value' })};