首页 > 解决方案 > 如何通过 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。我试图用其他帖子上推荐的非函数调用来做,但无法让它工作。

标签: javascriptreactjs

解决方案


您可以使用 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}))}
  }
}

推荐阅读