我正在尝试弄清楚如何将 Flow.js 类型与 compound React components. 一起使用
例如,假设我有组件 A
,如下所示:
type Props = {title: string};
const A = ({title}: Props) => <span>{title}</span>;
和 TitleProvider
像这样:
const TitleProvider = () => {
return React.cloneElement(this.props.children, {
title: 'Foo',
});
};
然后我将这两个组件用作复合组件,如下所示:
<TitleProvider>
<A />
</TitleProvider>
这将失败,因为对 React.createElement 的初始调用将创建 A
组件,而没有所需的 title
属性。
我想继续使用复合组件(我不想传递组件类或使用渲染 Prop )。我还希望 A
的 title 属性保持所需状态(我不想使用像 {title?: string}
这样的类型)。
有办法实现吗?
最佳答案
您可以尝试使用 React Hooks 和 Context api-s。
创建上下文提供者:
// @flow
import * as React from "react";
export const TitleContext: React.Context<{
title: string
}> = React.createContext({
title: string
});
const TitleProvider = (props: {children: React.Node}) => {
return <TitleContext.Provider value={{title: "Foo"}}>
{props.children}
<TitleContext.Provider>
};
接下来,创建使用 TitleProvider 的 A:
// @flow
import * as React from "react";
import {TitleContext} from "...";
const A = () => {
const {title} = useContext(TitleContext); // flow infer type 'string' for title
return <span>{title}</span>
};
最后复合TitleProvider和A:
<TitleProvider>
<A />
</TitleProvider>
关于reactjs - 将 Flow.js 与 React 复合组件结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50603164/