How to define typescript for React.Children.map

前端 未结 1 842
滥情空心
滥情空心 2021-02-13 08:49

I have a function that looks at the provided children and if a particular element type is found, it adds some properties to it automatically.

The function is called like

相关标签:
1条回答
  • 2021-02-13 09:40

    The problem is a couple of things. I started by changing children: Array<any> to children: React.ReactNode. You already have a check in there to narrow the type from ReactNode to ReactElement. The trick was 1. using the generic type arguments in isValidElement and 2. using a new variable with a type assignment on it elementType rather than dealing with and mutating the child argument. EnrichedChildren may need to be updated to match your use case.

    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
        }
      })
    
    0 讨论(0)
提交回复
热议问题