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

时间:2019-08-20 07:12:41

标签: reactjs

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

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

分隔符位于面包屑中的元素之间,并且位于面包屑中的最后一个元素之间,我不想放置分隔符。一幅图片,我不想显示最后一个V形(分隔线):

enter image description here

2 个答案:

答案 0 :(得分:4)

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可以保护您免受未定义的值的影响

答案 1 :(得分:1)

您可以使用index并检查其是否等于children数组的长度:

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