【问题标题】:Passing props through too many levels通过太多关卡传递道具
【发布时间】:2017-05-23 22:52:24
【问题描述】:

考虑一下

Parent component (prop: textColor)
intermediate component 1
intermediate component 2
intermediate component N
Component with text (needs textColor)

如何避免通过中间组件显式传递textColor

这是否是 Context 的一个很好的用例,即使它有因不同原因阻止其使用的警告?

【问题讨论】:

  • 如果您使用的是 redux,则将 textColor 存储在 Store 中,从存储中获取到您的任何组件中作为 props
  • @Kartik_Agarwal 没错,但这意味着那些可以作为道具访问store 的组件是容器,而不是代表性(又名简单)组件。这就是为什么我犹豫要不要做的原因,我认为那些在树下很深的组件应该很简单。

标签: reactjs


【解决方案1】:

按照 leo 的建议,使用上下文:

class ParentComponent extends React.Component {
    static childContextTypes = {
        someContext: React.PropTypes.string
    };

    getChildContext() {
        return {
            someContext: 'foo-bar'
        };
    }

}

那么第 N 个子组件会:

class NthChild extends React.Component {
    static contextTypes = {
        someContenxt: React.PropTypes.string
    };

    render() {
        // this.context.someContext is available here
    }
}

【讨论】:

  • 这仍然是最佳答案吗? react documentation 似乎强烈反对使用上下文。
  • @randomsolutions 我实际上不得不不同意。 context 是一项高级功能,如果您知道自己在做什么,那就没问题了。最大的问题是它是一个实验性的 API,所以它很可能会发生变化。 Redux Connect 函数使用上下文。见stackoverflow.com/questions/36428355/…
【解决方案2】:

如果textColor 不改变/不是状态的一部分,您可以将其定义为变量并按需导入。

否则,您应该使用上下文,因为这正是它的用例。

在某些情况下,您希望通过组件树传递数据,而不必在每个级别手动向下传递道具

【讨论】:

    猜你喜欢
    • 2020-01-17
    • 1970-01-01
    • 2021-09-13
    • 2019-10-30
    • 2019-03-27
    • 2019-08-09
    • 2019-12-14
    • 2022-01-19
    • 1970-01-01
    相关资源
    最近更新 更多