React.Children.forEach如何提前终止遍历

当使用 React.Children.forEach 去遍历 React children 时,如何提前终止循环?

forEach 中使用 breakreturn 是没有用的。

换种思路,可以使用 React.Children.toArraychildren 转换为数组,再对数组进行遍历就有办法提前终止了。

const childList = React.Children.toArray(children);
for (let [index, child] of childList.entries()) {
  // 比如索引为1时终止遍历
  if (index === 1) {
    break;
  }
}
如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注