在组件中映射道具时,如何为道具的子级编写排除?

问题描述

处理我的 D.R.Y.我正在尝试将父组件的数据传递给子组件,以便我可以重新使用子组件。鉴于我拥有的父组件:

<Child data="data">
  <svg viewBox={'0 0 500 500'}>
    <path d="path" />
  </svg>
  <p>This is some text</p>
</Child>

Child.js:

import React from 'react'
import Foo from '../Foo'
import { Container,Svg,Div,Text } from './ChildElements'

const Child = props => {
  return (
    <>
      <Container>
        {props.children.map((c,k) => {
          if (c.type === 'svg')
            return (
              <Svg key={k} viewBox={c.props.viewBox}>
                {c.props.children}
              </Svg>
            )
        })}
        <Div>
          {props.children.map((c,k) => {
            if (c.type === 'p') return <Text key={k}>{c.children}</Text>
          })}
          <Foo bar={props.data} />
        </Div>
      </Container>
    </>
  )
}
export default Child

child.js 硬编码:

import React from 'react'
import Foo from '../Foo'
import { Container,Text } from './ChildElements'

const Child = ({data}) => {
  return (
    <>
      <Container>
        <Svg viewBox={'0 0 500 500'}><path d="path" /></Svg>
        <Div>
          <Text>Hard coded text</Text>
          <Foo bar={data} />
        </Div>
      </Container>
    </>
  )
}

export default Child

子组件可以工作,但如果我从 Text 中排除 <p>This is some text</p> (Parent),应用程序会抛出以下错误

TypeError: props.children.map 不是函数

在终端中我收到一个 ESLint 错误

array.prototype.map() 期望在箭头函数结束时返回一个

如果我不知道父组件中将包含什么内容,我如何在传递给子组件时为 SvgText 设置条件?

研究:

解决方法

这就是创建 React.Children.map 的目的。当提供多个子项时, props.children 将是一个数组,并且您的代码有效。但是,当只提供一个子项或不提供子项时,props.children 将不是数组,从而导致您的代码需要考虑无、一个或多个子项的每个变体。 React.Children.map 的工作方式与普通数组 map 类似,但可以优雅地处理这三种情况。

您可能还想查看 React.cloneElement 来处理您的元素创建代码,但在您的情况下,我认为您只想过滤一些元素,以便您可以返回它们。

    {React.Children.map(props.children,(c,k) => {
      if (c.type === 'svg')
        return c
    })}

还有一个 React.Children.toArray,如果您愿意,它允许您使用 filter

最后,我应该注意使用索引作为键是没有意义的。 React 已经使用顺序来识别孩子。如果您通过提供索引作为键来增强该功能,则不会改变行为。用于生成 Svg 元素的数据中应存储一个键,以便正确识别表示相同数据的 Svg 元素。