javascript - 将道具传递给子组件问题
问题描述
我正在尝试将道具传递给子组件进行反应,但是当我控制台记录它时它根本没有出现在道具中。连钥匙things
都没有出现。对此的任何帮助将不胜感激。
export default class Child extends Component {
constructor(props) {
super(props);
console.log(props)
}
render() {
console.log(this.props)
return (
<div>
Test
</div>
);
}
}
class Parent extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Router>
<div>
<Route path='/testing' things="yes" component={Child} />
</div>
</Router>
</div>
);
}
}
}
const connectedParent = connect()(Parent);
export { connectedParent as Parent };
解决方案
在您的父组件中,将 Route 替换为以下内容,
<Route
path='/testing'
render={(props) => <Child {...props} things="yes" />}
/>
让我知道它是否有效。
说明:当您使用 时<Route path='/testing' things="yes" component={Child} />
,您没有将道具传递给 Child 组件,而是传递给 Route 组件并且它忽略了它。
在 Route 中将 props 传递给 Child 组件的另一种方法是:
<Route
path='/testing'
component={() => <Child things="yes" />}
/>
但是使用方法,您会丢失 Route 道具,例如位置,历史记录和其他道具,并且根据文档:
当您使用组件道具时,路由器使用 React.createElement 从给定组件创建一个新的 React 元素。这意味着如果您为组件属性提供内联函数,您将在每次渲染时创建一个新组件。这会导致现有组件卸载和新组件安装,而不是仅仅更新现有组件。
所以我们留下了我建议的方法,即
<Route
path='/testing'
render={(props) => <Child {...props} things="yes" />}
/>
在这里,您将诸如事物之类的道具传递给子组件本身,而不是路由,并且 Route 的渲染方法也提供了 Route 道具。所以请始终记住将它的 props 作为 {...props} 传递,这样您就可以在 Child 组件中访问 Route props,并且在路由时不会遇到任何问题。
推荐阅读
- compression - 库在 zlib 压缩/放气代码中的哪个位置决定应该将块作为未压缩的形式复制到压缩流中?
- python - HTML 返回并列出数据库中的所有条目,即 url。但我不知道如何使它成为实际的链接
- c++ - `=` 分配给新的 std::string 究竟分配了什么?
- php - 如何在当前用户的 eloquent 模型中访问方法
- nelmioapidocbundle - 如何使用 NelmioApiDocBundle(4.x) 为 /api/login_check 和 /api/token/refresh 生成 API 文档
- xamarin.forms - Xamarin Forms:WebView 加载时间非常长
- nestjs - Nestjs 和类验证器 - 至少一个字段不应为空
- blank-line - 如何在每行之间系统地添加新行
- php - php 错误未捕获的错误:调用未定义的函数 mysqli_fetch_all()
- android - 使用 NullPointerException 权限调用 LocationUpdatesService 时应用程序崩溃