flowtype - 如何在流中的父组件和子组件之间同步泛型类型?
问题描述
我有两个协同工作的组件(父子关系),它们必须共享通用类型。因此,当您使用一种特定类型实例化父组件时,必须限制所有子组件在其泛型上仅采用该类型。
例如,我希望这失败:
<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复制的链接
解决方案
推荐阅读
- ios - Setting up data source for Sections in UITableView Based off of Data from Backend
- windows - 在 Windows 上使用 mp.get_property("path") 空格从 MPV 播放器返回的路径错误
- c# - Unity - 如何让我的跳跃动画循环正常工作?
- sql - How to use LIKE wild card on subquery?
- android - 我添加了配置文件活动,然后添加了动态图像配置文件和用户名。在我这样做之后,导航按钮根本不起作用
- java - Testing 4 numbers to see if its has 3 unique numbers
- java - 片段中的 Recyclerview 未立即显示警报对话框结果
- jquery - 如何从中获取价值/文本
- c++ - Qt5中的C++回调函数和pigpio库
- c# - 取消广告后不奖励