React 将 props 向下传递给所有后代组件

React pass props down to all descendant Components

用例是我想 "effortlessly" 将某个道具值传递给所有后代组件。不确定这在 React 中是否可行。

所以不要这样做:

class Parent extends Component {
    constructor() {
        super(props);
        this.props.componentID = "123456";
    }
    render() {
        return <Child1 componentID={this.props.componentID} />
    }
}

class Child1 extends Component {

    render() {
        return <Child2 componentID={this.props.componentID} />
    }
}

class Child2 extends Component {

    render() {
        return <div>{this.props.componentID}</div>
    }
}

做这样的事情:

class Parent extends Component {
    constructor() {
        this.props.componentID = "123456";
    }

    passComponentIDToAllDescendantComponents() {
        // Some super nifty code
    }

    render() {
        return <Child1 />
    }
}

// etc...

感谢帮助

您可以使用 Context 功能将数据向下传递到 children。在您的情况下,它可能看起来像这样:

class Parent extends Component {
    getChildContext() {
        return {componentID: "123456"};
    }
    render() {
        return <Child1 />
    }
}

Parent.childContextTypes = {
    componentID: React.PropTypes.string
};

class Child1 extends Component {

    render() {
        return <Child2 />
    }
}

class Child2 extends Component {

    render() {
        return <div>{this.context.componentID}</div>
    }
}

Child2.contextTypes = {
    componentID: React.PropTypes.string
};