How to define typescript for React.Children.map

前端 未结 1 845
滥情空心
滥情空心 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 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(child)) {
          return child
        }
    
        let elementChild: React.ReactElement = child
        if (child.props.children) {
          elementChild = React.cloneElement(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)
提交回复
热议问题