【发布时间】: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