【问题标题】:Access all children component of a React component访问 React 组件的所有子组件
【发布时间】:2017-11-03 09:38:54
【问题描述】:

我有反应组件 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>

【问题讨论】:

  • 你能描述一下你想对组件 B 执行什么样的操作,以及你是否将任何属性传递给它们?为了添加Bs组件,你是怎么做的?也许您有一个数组或其他结构来保存数据并且您正在迭代它,或者您只是明确地这样做?

标签: javascript reactjs ecmascript-6


【解决方案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

你需要传递这个包含所有子组件的 {childrenProps}。

【讨论】:

    【解决方案2】:

    所以我想通了。我将ref 分配给每个&lt;B/&gt;,并将其存储在一个数组中:

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

    【讨论】:

    • 只要你意识到在 React 中使用 ref 的缺点。组件变为不受控制的组件,然后道具侦听器停止工作,您负责生命周期。反正这是我的理解
    猜你喜欢
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 2017-11-12
    • 2023-01-12
    相关资源
    最近更新 更多