如何通过this.props.children()传递道具而不是this.props.children

时间:2018-05-11 13:23:58

标签: javascript reactjs

我想通过盖茨比布局传递所有道具。例如:

15:11:29: Array [
15:11:29:   Object {
15:11:29:     "Citta": "Milano",
 15:11:29:     "Data": "9/08/2018 ",
15:11:29:     "Foto": "x",
15:11:29:     "Nome": "Musica pop",
15:11:29:     "Ora": "18:30:00",
15:11:29:   },
15:11:29:   Object {
15:11:29:     "Citta": "Ancona",
15:11:29:     "Data": "9/05/2018",
15:11:29:     "Foto": "x",
15:11:29:     "Nome": "Food porn",
15:11:29:     "Ora": "21:30:00",
15:11:29:   },
15:11:29:   Object {
15:11:29:     "Citta": "miami",
15:11:29:     "Data": "12/12/2018",
15:11:29:     "Foto": "x",
 15:11:29:     "Nome": "musica jazz",
 15:11:29:     "Ora": "21:30:00",
 15:11:29:   },
 15:11:29: ]

这里要注意的是,这是一个函数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()。我尝试使用其他帖子推荐的非函数调用方式,但无法使其工作。

1 个答案:

答案 0 :(得分:1)

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