【问题标题】:React pass props down to all descendant ComponentsReact 将 props 传递给所有后代组件
【发布时间】:2016-08-06 16:01:22
【问题描述】:

用例是我想“毫不费力地”将某个 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...

感谢您的帮助

【问题讨论】:

  • 不要修改props..使用setState
  • 你应该看看 React 的 Context:facebook.github.io/react/docs/context.html
  • @madox2 谢谢!!!正是我想要的
  • @madox2,您的评论应标记为答案。在我看到 React 文档之前,我正要写下这是不可能的。我觉得传递道具确保代码可读。
  • 警告:确保有充分的理由以这种方式以不可见的方式将 props 沿树向下传递(因为您的组件 jsx 不再能说出全部真相)。另外,在撰写本文时,ReactJS 文档说这是一个实验性功能,因此它可能会在未来发生变化,从而破坏您的应用程序。

标签: javascript reactjs children descendant


【解决方案1】:

您可以使用Context 功能将数据向下传递给孩子。在您的情况下,它可能如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-17
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多