首页 > 解决方案 > 如何为 React.Children.map 定义打字稿

问题描述

我有一个查看提供的子元素的函数,如果找到特定的元素类型,它会自动向它添加一些属性。

该函数是这样调用的:

render () {

    const { children, name, className } = this.props;

    return (
        <div className={className}>
            {this.enrichRadioElements(children, name)}
        </div>
    )
}

它是这样实现的:

enrichRadioElements = (children: Array<any>, name: string) => (
    React.Children.map(children, child => {
        if (!React.isValidElement(child)) {
            return child;
        }

        //@ts-ignore
        if (child.props.children) {
            child = React.cloneElement(child, {
                //@ts-ignore
                children: this.enrichRadioElements(child.props.children, name)
            });
        }

        if (child.type === Radio) {
            return React.cloneElement(child, { 
                onChange: this.handleFieldChange,
                selectedValue: this.state.selectedValue,
                name: name
            })
        }
        else {
            return child;
        }
    })
)

这两条//@ts-ignore评论是我试图通过编写满足打字稿的代码来摆脱的。如果我删除第一个,我看到的错误消息是:

类型“{}”上不存在属性“子项”。(ts-2339)

如何正确修改我的代码以便删除//@ts-ignore评论?我确实去了 child.props 的定义,我发现了这个:

interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
    type: T;
    props: P;
    key: Key | null;
}

它看起来有任何类型的“道具”(如果我没看错的话),但打字稿无法识别 children 属性。

标签: reactjstypescript

解决方案


问题是几件事。我首先更改children: Array<any>children: React.ReactNode. 您已经在那里进行了检查以将类型从 ReactNode 缩小到 ReactElement。诀窍是 1. 使用泛型类型参数 inisValidElement和 2. 使用带有类型赋值的新变量,elementType而不是处理和改变child参数。EnrichedChildren可能需要更新以匹配您的用例。

interface EnrichedChildren {
  onChange(): void
  selectedValue: string
  name: string
  children?: React.ReactNode
}

enrichRadioElements = (children: React.ReactNode, name: string): any =>
  React.Children.map(children, child => {
    if (!React.isValidElement<EnrichedChildren>(child)) {
      return child
    }

    let elementChild: React.ReactElement<EnrichedChildren> = child
    if (child.props.children) {
      elementChild = React.cloneElement<EnrichedChildren>(elementChild, {
        children: this.enrichRadioElements(elementChild.props.children, name),
      })
    }

    if (elementChild.type === 'Radio') {
      return React.cloneElement(elementChild, {
        onChange: () => {},
        selectedValue: 'value',
        name: name,
      })
    } else {
      return elementChild
    }
  })

推荐阅读