如何获取组件的React.Children

时间:2019-02-19 14:38:10

标签: reactjs

我正在学习React。现在,我试图了解如何正确使用React.Children,但是尽管进行了多次尝试和阅读文档,但我还是永久失败。恐怕我忽略了一些琐碎的事情。 这是一个虚拟的例子。

请您解释一下,为什么React.Children.count为0?我期望5.我该怎么做?

class Author extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        {this.props.Name} {this.props.Surname}
      </div>
      )
  }
}


class Express extends React.Component {
  constructor(props) {
    super(props);
    this.doClick = this.doClick.bind(this);
  }

  doClick() {
     alert(React.Children.count(this.props.children)); // outcome is 0 (?)
  }

  render() {
    return (
      <div onClick={this.doClick}>
        <div>Science</div>
        <Author Name="Mario" Surname="Puzzo"/>
        <Author Name="Maria" Surname="Devita"/>
        <div>Literature</div>
        <div>History</div>
      </div>
    );
  }
}

ReactDOM.render(<Express />, document.getElementById("root"));

2 个答案:

答案 0 :(得分:1)

反应文档:

React.Children.count(children):
    Returns the total number of components in children, equal to the number of times that a callback passed to map or forEach would be invoked.

在您的示例中,我可以得出结论,您的 Express 组件没有任何子代,因此将React.Children.count(this.props.children)的结果设为0是正常的。另外,如果您尝试在 Author 组件中获得孩子的数量,则结果应该相同。

尝试像这样重新定义它:

import React from 'react';

const Author = ({ children, id }) => {
    alert(`child ${id}: ${React.Children.count(children)} children`); // outcome is 2 for the first child Author and 1 for the second
    return (
        <>
            {children}
        </>
    )
};

const Express = () => (
      <div>
          <div>Science</div>
          <Author id="1">
              <div>Mario Puzzo</div>
              <div>Mario2 Puzzo2</div>
          </Author>
          <Author id="2">
              <div>Maria Devita</div>
          </Author>
          <div>Literature</div>
          <div>History</div>
      </div>
);

export default Express;

要获得更多说明,请尝试访问此链接React.children

答案 1 :(得分:0)

在您的示例中,Author组件没有任何子代。从提供的代码中,我们无法确定Express组件是否传递了任何子代。

在Express组件中(如果使用):这是孩子

,然后在您的作者组件View::composer('*', function ($view) { $view->with('home_references', Cache::remember('home_references', 60, function() { return Reference::where('position', 'home')->orderBy('order', 'asc')->get();})); $view->with('informations', Cache::remember('informations', 60, function() { return ContactInformation::first();})); $view->with('header_posts', Cache::remember('header_posts', 60, function() { return Post::latest()->limit(4)->get();})); }); 中  您应该得到的结果不为0。