遍历孩子,找到最后一个元素

托马斯·瓦兹奇克(Tomasz Waszczyk)

我研究面包屑成分,并遍历以下子项:

renderChildren = () => {
  const { children, divider } = this.props;
  return (
    React.Children.map(children, child => (
      <>
        {child}
        {divider}
      </>
    ))
  );
}

分隔符位于面包屑中的元素之间,而位于面包屑中的最后一个元素上,我不想放置分隔符。一张图片,我不想显示最后一个人字形(分隔线):

在此处输入图片说明

Medet Tleukabiluly
renderChildren = () => {
  const { children, divider } = this.props;
  return (
    React.Children.map(children, (child, index) => (
      <>
        {child}
        {(index < children.length - 1) && divider}
      </>
    ))
  );
}

更新:

const children: React.ReactNode Object is possibly 'null' or 'undefined'.ts(2533)

不在此答案的范围内,但可以处理此情况

renderChildren = () => {
  const { children, divider } = this.props;
  if (children) { // this fixes error above
    return (
      React.Children.map(children, (child, index) => (
        <>
          {child}
          {(index < children.length - 1) && divider}
        </>
      ))
    );
  }
  return null
}

出现该错误是因为您将prop定义为children?: ReactNode,因为它是可选的TypeScript可以使您免受未定义的值的影响

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章