Reactjs 通过太多关卡传递道具

Reactjs 通过太多关卡传递道具,reactjs,Reactjs,想想这个 Parent component (prop: textColor) intermediate component 1 intermediate component 2 intermediate component N Component with text (needs textColor) 如何避免显式地通过中间组件传递textColor 这是一个很好的上下文用例,即使它有警告,由于不同的原因不鼓励使用它吗?如果textColor没有改变/不是状态的一部分,您可以将它定义为一个变

想想这个

Parent component (prop: textColor)
intermediate component 1
intermediate component 2
intermediate component N
Component with text (needs textColor)
如何避免显式地通过中间组件传递
textColor


这是一个很好的上下文用例,即使它有警告,由于不同的原因不鼓励使用它吗?

如果
textColor
没有改变/不是状态的一部分,您可以将它定义为一个变量,并根据需要导入它

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

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


正如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
    }
}

如果您正在使用redux,那么将textColor存储在
store
get from store中,作为
props
@Kartik\u Agarwal将其作为属性存储到任何组件中,这是正确的,但这意味着可以访问
store
的组件是容器,而不是代表性(又称简单)组件。这就是为什么我犹豫不去做,我认为那些在树的深处的组件应该很简单。这仍然是最好的答案吗?这似乎强烈反对使用上下文解决方案,但实际上我不同意<代码>上下文是一项高级功能,如果您知道自己在做什么,就可以了。最大的问题是它是一个实验性的API,所以很可能会发生变化。Redux Connect函数使用上下文。看见