React将道具传递给所有子组件
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
};
相关文章:
- React重新渲染但未显示正确的组件
- React组件等待所需道具进行渲染
- 如何在react js中将值从一个组件发送到另一个组件
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- React组件-设置页面标题
- 为react组件传递道具的最佳方式
- react组件中的绑定方法
- 如何在react js中移动第二个组件
- 如何在react路由器的组件中使用参数
- React+Redux性能优化与组件ShouldUpdate
- React-将jSON数据传递给子组件的子组件
- React js更改状态不会更新组件
- 加载服务器端渲染的React组件后执行脚本
- React ClickDrag子组件回调
- 如何在渲染函数中检查 react 中子组件的状态
- 以最封装的方式封装/封装ScalaJS react js组件(react stick)
- bind():您正在将一个组件方法绑定到该组件.React会自动为您执行此操作
- 如何将值从父组件传递到子组件(react)
- 将函数从HOC传递到组件(React, React native)
- 根据屏幕大小以不同的顺序呈现组件(React)