0

我有一个呈现动态子级的组件,这些子级中的每一个都需要分配给它们的 ref,例如ref={'childID' + index}

一旦孩子们加载完毕,我就需要一种方法来循环孩子们并获得他们的参考。

有什么办法吗?

4

2 回答 2

2

您应该能够this.refs使用Object.keys.

Object.keys(this.refs).forEach(key =>
  const ref = this.refs[key];
  ...
);
于 2016-02-24T15:56:55.267 回答
0

您可以使用ref道具的回调样式来收集所有参考。

这是一个粗略的例子,说明它的外观。

var refs = {};

function refCollector(id) {
  return function(element) {
    refs[id] = element;

    if(allRefsCollected()) {
      // do some work with all refs
    }
  }
}

function allRefsCollected() {
  return Object.keys(refs).length >= children.length;
}

return children.map((Child, index) => {
  return <Child ref={refCollector(index)} />;
});

allRefsCollected返回 true 时,你会知道所有的孩子都已经被渲染并且refs将是一个对象,映射idelement.

于 2016-02-24T14:40:56.780 回答