Javascript 如何检查有多少 React 孩子拥有某个道具?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34466068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:22:39  来源:igfitidea点击:

How to check how many React children have a certain prop?

javascriptreactjs

提问by Tomasz Ga?kowski

I have two types of components. Let's call them Outer and Inner. Imagine something like this:

我有两种类型的组件。让我们称它们为外部和内部。想象一下这样的事情:

<Outer>
    <h4>{this.prop.title} ({this.state.withX}/{this.state.total})</h4>
    <Inner isX/>
    <Inner isX/>
    <Inner/>
    <Inner/>
</Outer>

I have this function:

我有这个功能:

getInitialState: function() {
    return {
        total: React.Children.count(this.props.children),
        withX: /// ??? ///
    };
}

How do I get that value? I was trying to get something like this:

我如何获得该值?我试图得到这样的东西:

withX: function() {
    var counter = React.Children.forEach(this.props.children, function(child) {
         // if...
         return //something
    });
return counter;
}

But... I feel it'll get me nowhere.

但是......我觉得它不会让我无处可去。

采纳答案by Michelle Tilley

When you iterate over the children, you can inspect their props. For instance, using the forEachmethod you have above, you could do something like this:

当您迭代孩子时,您可以检查他们的道具。例如,使用forEach上面的方法,您可以执行以下操作:

withX: function() {
  var counter = 0;
  React.Children.forEach(this.props.children, function(child) {
    if (child.props.isX) counter++;
  });
  return counter;
}

React also provides a toArrayhelperthat lets you do the same thing using the nice array methods JS provides:

React 还提供了一个toArray帮助器,可以让您使用 JS 提供的漂亮的数组方法来做同样的事情:

return React.Children.toArray(this.props.children).filter(function(child) {
  return child.props.isX;
}).length;

If you're using ES6, can do this quite succinctly with an arrow function:

如果您使用的是 ES6,可以使用箭头函数非常简洁地完成此操作:

return React.Children.toArray(this.props.children).filter(c => c.props.isX).length;

The only catch is that, if Outeris doing the counting, then Outeralso needs to render the h4. Here's a full example:

唯一的问题是,如果Outer正在进行计数,则Outer还需要渲染h4. 这是一个完整的例子:

const App = React.createClass({
  render() {
    return (
      <Outer title="Things">
        <Inner isX/>
        <Inner isX/>
        <Inner/>
        <Inner/>
      </Outer>
    );
  }
});

const Outer = React.createClass({
  getInitialState() {
    return {
      total: React.Children.count(this.props.children),
      withX: this.countChildrenWithX(this.props.children)
    };
  },

  countChildrenWithX(children) {
    const { toArray } = React.Children;
    return toArray(children).filter(c => c.props.isX).length;
  },

  render() {
    return (
      <div>
        <h4>{this.props.title} ({this.state.withX}/{this.state.total})</h4>
        <hr />
        {this.props.children}
      </div>
    );
  }
});

const Inner = React.createClass({
  render() {
    return <div>Inner - withX = {String(!!this.props.isX)}</div>;
  }
});

And here's a working JS Binto demonstrate: https://jsbin.com/xameyun/edit?js,output

这里的工作JS斌证实:https://jsbin.com/xameyun/edit?js,output

回答by Chris Edwards

React now has React.Children.count(children)method documented here https://facebook.github.io/react/docs/react-api.html#react.children.count

React 现在React.Children.count(children)在此处记录了方法https://facebook.github.io/react/docs/react-api.html#react.children.count

UPDATE: upon reflection, I'm not sure this actually answers the question, but will leave here anyway as people have already voted on it.

更新:经过反思,我不确定这是否真的回答了这个问题,但无论如何都会离开这里,因为人们已经对其进行了投票。