[英]React pass props down to all descendant Components
用例是我想“毫不費力地”將某些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...
謝謝您的幫助
您可以使用“ 上下文”功能將數據傳遞給子項。 在你的情況下,它可能看起來像這樣:
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
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.