网站搜索

javascript - React 将 props 传递给所有子孙组件


用例是我希望能够“轻松地”将某些 prop 值传递给所有子组件。不确定在 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...

谢谢你的帮助

答案#1

你可以使用上下文功能将数据传递给子组件。在你的情况下,它可能看起来像这样:

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
};