Reactjs 将Flow.js与React复合组件一起使用
我正在尝试找出如何将Flow.js类型与 例如,假设我有组件Reactjs 将Flow.js与React复合组件一起使用,reactjs,flowtype,Reactjs,Flowtype,我正在尝试找出如何将Flow.js类型与 例如,假设我有组件A,如下所示: type Props = {title: string}; const A = ({title}: Props) => <span>{title}</span>; const TitleProvider = () => { return React.cloneElement(this.props.children, { title: 'Foo', }); }; 然后
A
,如下所示:
type Props = {title: string};
const A = ({title}: Props) => <span>{title}</span>;
const TitleProvider = () => {
return React.cloneElement(this.props.children, {
title: 'Foo',
});
};
然后我将这两个组件用作复合组件,如下所示:
<TitleProvider>
<A />
</TitleProvider>
这将失败,因为对React.createElement的初始调用将创建A
组件,而不包含所需的title
prop
我想继续使用复合组件(我不想传递组件类或使用渲染道具)。我还希望A
的title prop按需要保留(我不希望使用类似{title?:string}
的类型)
有没有办法做到这一点?您可以尝试使用React挂钩和上下文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>
};
/@flow
从“React”导入*作为React;
导出常量TitleContext:React.Context=React.createContext({
标题:字符串
});
const TitleProvider=(道具:{children:React.Node})=>{
返回
{props.children}
};
接下来,创建一个使用TitleProvider的:
// @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>
};
/@flow
从“React”导入*作为React;
从“…”导入{TitleContext}”;
常数A=()=>{
const{title}=useContext(TitleContext);//流推断title的类型“string”
返回{title}
};
最后,复合TitleProvider和A:
<TitleProvider>
<A />
</TitleProvider>
不确定这是否有帮助,但您可以提供默认道具A.defaultProps={title:'}
Flow足够聪明,可以处理默认的props。想象一下下面的组件const B=({title}:Props)=>{title.length?title:'empty'}
不仅流会抱怨,而且你也会得到TypeError.IMHO,这有点违反了组件的概念,因为我们想在不知道如何的情况下对A
组件及其道具进行推理所以,你不想放松A
的道具类型是很好的,但是TitleProvider
的逻辑是不正确的(也许可以在那里定义一些多余的道具?).这个问题背后的想法更多的是让flow.js与cloneElement
一起工作,不过还是要感谢您的回答!