reactjs - React 组件,使用嵌套组件访问 this.props
问题描述
我遇到了一个小挑战,那就是如何让子组件访问 this.props 之类的东西(特别是寻找 this.props.history)。我的代码本质上是;
// app.js, setup a router...
return (
<Router>
<Route path="/componenta" component={ComponentA}/>
</Router>
);
// Component A has access to this.props
class ComponentA extends Component {
componentDidMount() {
console.log('The props are ', this.props);
}
render() {
return (
<div>
<h1>Hello from Component A</h1>
<ComponentB/>
</div>
);
}
}
// ComponentB does not have access to this.props,
// and I know it is because it is a sub-component here.
class ComponentB extends Component {
componentDidMount() {
console.log('The props are ', this.props);
}
render() {
return (
<div>
<h1>Hello from Component B</h1>
</div>
);
}
}
我觉得这是我想念的简单的东西,有什么建议吗?
谢谢。
解决方案
欢迎来到 SO,我看到你没有传递任何东西prop
,ComponentB
所以你必须做这样的事情;
<ComponentB history={this.props.history}/>
然后你就可以history
在你的ComponentB
推荐阅读
- c# - 如何在 dotnet pack nuget 包中包含来自构建输出 (dacpac) 的非 dll 文件?
- python - 从给定数据框的一列的所有行中提取粗体字母
- sql - 如何查找只有一个值的列 - Postgresql
- python - 如何在python中标记构造线?
- android - 上传到 Google Play 不同的指纹
- java - 设置活动时出现 NullPointerException
- javascript - 在 Google 表格脚本中的大型非线性单元格范围上使用 setValue
- python - 用 Sublime Text 3 编写的 Python 代码无法运行
- regex - 从带有附加条件的字符串中提取一个 8 位数字
- node.js - 使用 MQTT 和 Javascript 从 Azure IoT 读取数据