首页 > 解决方案 > 如何在流中的父组件和子组件之间同步泛型类型?

问题描述

我有两个协同工作的组件(父子关系),它们必须共享通用类型。因此,当您使用一种特定类型实例化父组件时,必须限制所有子组件在其泛型上仅采用该类型。

例如,我希望这失败:

<Parent onChange={console.log} value={5}>
    <Child value="5"/>
</Parent>

但是,我无法完成这项工作(AKA 失败)。我查看了有关抽象组件的流程文档,但我认为这在这种情况下无济于事。这是我迄今为止尝试过的一个小的复制品:

//@flow
import type { ChildrenArray, Element } from 'react'
import React, { Children, type Node } from 'react'

type ParentProps<T> = {
  onChange: (value: T) => void,
  value: T,
  children: ChildrenArray<Element<typeof Child>>,
}

export function Parent<T>({
  children,
  value,
  onChange,
}: ParentProps<T>) {
  const childComponents = Children.map(children, (child) => 
        React.cloneElement(child, {
          onSet: () => {
            onChange(child.props.value)
          },
        })
    )
    return <div>{childComponents}</div>
}

type ChildProps<T> = {
  children?: Node,
  value: T,
  onSet?: () => void,
}

const Child = <T>({children, onSet}: ChildProps<T>) => {
  return <button onClick={onSet}>{children}</button>
}

<Parent onChange={console.log} value={5}><Child value="5"/></Parent>

这是TryFlow复制的链接

标签: flowtype

解决方案


推荐阅读