我想通过盖茨比布局传递所有道具。例如:
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}))}
}
}