javascript - 如何通过 this.props.children() 而不是 this.props.children 传递道具
问题描述
我想通过 gatsby 布局传递我所有的道具。例如:
import React, { Component } from 'react';
export default class ExampleLayout extends Component {
render() {
const { data } = this.props;
return <div>{this.props.children(data)}</div>; // --> this does not work, but I want to do something like this
}
}
这里需要注意的是,这是this.props.children()
作为函数调用而不是非函数调用this.props.children
。我试图用其他帖子上推荐的非函数调用来做,但无法让它工作。
解决方案
您可以使用 React.Children.map 或 React.Children.forEach 并遍历组件的所有直接子级并将它们传递给您的道具。例如:
import React, { Component, Children } from 'react';
export default class ExampleLayout extends Component {
render() {
const { data } = this.props;
const children = this.props.children()
{Children.map(children, child => React.cloneElement(child, { ...data}))}
}
}
推荐阅读
- python - Python - 在熊猫数据框中使用多个替换来拆分和替换列表的一部分
- c++ - std::stringstream 是否有两个缓冲区,因此有两个标记?
- powershell - 使用 PowerShell 过滤 JSON 文件
- r - 如何根据另一列的相等性对列的值求和并创建新的数据框
- libreoffice-calc - Excel 到 Libreoffice 的宏转换 - RefreshTable
- spring - 跨 Spring Boot Server 运行持久化的状态数据示例
- f# - 可以在完整的 Web 应用程序中使用 F#
- redux - 反应 redux createSlice 或 createReducer
- c# - 如何触发 ViewModel 中的方法?
- vb.net - 创建一个列表(位图)绘制一个列表(字符串)