reactjs - 将 Flow.js 与 React 复合组件结合使用

标签 reactjs flowtype

我正在尝试弄清楚如何将 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/

相关文章:

javascript - Reactjs 在 keyup 上获取事件键码

flowtype - 如何指定 Flowjs 中所需的两个 Prop 之一?

casting - 如何强制Flow将值强制转换为另一种类型?

javascript - 如何定义 Redux Actions 的 Flow 类型?

node.js - babel 未剥离流程的类型提示

javascript - 与错误 Prop 一起使用时,Formik 字段会失去焦点

reactjs - 在 React 中 axios http 调用后打开 bootstrap 模式

javascript - 如何在返回函数内迭代数组的数组 - ReactJS

javascript - 是否可以关闭所需的流注释?

reactjs - 与 3rd 方脚本安全地共享 Redux 状态