首页 文章

访问React组件的所有子组件

提问于
浏览
1

我有反应组件A,它呈现一个表 . 表中其中一列的数据通过另一个组件B呈现,因此 <B/><A/> 的子项 . 每当用户点击页面上的任何地方时,我想在 <B/> 上执行一些操作 . 此单击事件侦听器在 A 中定义 . 如何从类 A 内循环所有 <B/>s ?我的组件结构是这样的:

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

我遇到了 React.Children.forEach ,但是当孩子们通过 this.props.children 作为道具传递时,这很有用;即当代码是这样的:

<A>some markup</A>

2 回答

  • 1
    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 component to child components
     }));
    
      // to access you can use this.props.data or this.props.method in child component
    

    你需要传递这个包含所有子组件的 .

  • 2

    所以我明白了 . 我给了每个 <B/> ref ,并将其存储在一个数组中:

    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
      }
    }
    

相关问题