最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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
  }
}
发布评论

评论列表(0)

  1. 暂无评论