javascript - Access all children component of a React component - Stack Overflow

I have react ponent A which renders a table. Data for one of the columns in the table is rendered throu

I have react ponent A which renders a table. Data for one of the columns in the table is rendered through another ponent B, so <B/> is child of <A/>. I want to perform some action on <B/> whenever user clicks anywhere on the page. This click event listener is defined inside A. How can I loop through all <B/>s from inside class A? My ponent structure is something like this:

class A extends React.Component {
   <B/>
   <B/>
   <B/>
   <B/>
};

I came across React.Children.forEach, but that is useful when children are passed as props via this.props.children; i.e. when the code is something like this:

<A>some markup</A>

I have react ponent A which renders a table. Data for one of the columns in the table is rendered through another ponent B, so <B/> is child of <A/>. I want to perform some action on <B/> whenever user clicks anywhere on the page. This click event listener is defined inside A. How can I loop through all <B/>s from inside class A? My ponent structure is something like this:

class A extends React.Component {
   <B/>
   <B/>
   <B/>
   <B/>
};

I came across React.Children.forEach, but that is useful when children are passed as props via this.props.children; i.e. when the code is something like this:

<A>some markup</A>
Share Improve this question edited Nov 3, 2017 at 10:26 darKnight asked Nov 3, 2017 at 9:38 darKnightdarKnight 6,48115 gold badges58 silver badges93 bronze badges 1
  • Can you describe what kind of action you want to perform on ponent B and if you are passing any property to them? In order to add Bs ponent, how are you doing that? Maybe you have an array or another structure that holds the data and you are iterating through it or you are doing it just explicitly? – parecementeria Commented Nov 3, 2017 at 11:22
Add a ment  | 

2 Answers 2

Reset to default 4
const childrenProps = React.Children.map(this.props.children,
 (child) => React.cloneElement(child, {
    data : this.state,
    method : this.method.bind(this)
   // here you can pass state or method of parent ponent to child ponents
 }));

  // to access you can use this.props.data or this.props.method in child ponent

you need to pass this {childrenProps} which include all child ponents.

So I figured it out. I gave ref to each <B/>, and stored it in an array:

class A extends React.Component {
  collectRefs = [];
  <B ref={b => {this.collectRefs.push(b)}}/>
  <B ref={b => {this.collectRefs.push(b)}}/>
  <B ref={b => {this.collectRefs.push(b)}}/>

  for(const b of collectRefs) {
    // do stuff
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744265950a4565863.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信