【问题标题】:What is proper type for React's children as function?React 儿童作为函数的正确类型是什么?
【发布时间】:2019-08-21 05:06:23
【问题描述】:

我将孩子作为函数传递,将 React.ReactNode 返回到 Provider HOC,如下所示:

<Provider variables={{ id: "qwerty" }}>
  {data => (
    <ExampleComponent data={data} />
  )}
</Provider>

这是一个提供者组件示例代码:

type Props = {
  id: string;
  children: any; // What type should be put here?
};

const Provider: React.SFC<Props> = ({ id, children }) => {
  const { data, loading, error } = useQuery<req, reqVariables>(query, {
    variables: { id }
  });

  if (loading) return "Loading...";
  if (error) return "Error";
  if (!data) return "No data";

  return children(data);
}

如果我没有为children 指定任何类型,所以将其默认为React.ReactNode,那么return children(data); 行会显示错误:

无法调用类型缺少调用签名的表达式。键入'字符串 |号码 |布尔值 | {} | ReactElement ReactElement 组件)> |空) | (新(道具:任何)=> 组件)> |反应节点数组 | ReactPortal' 没有兼容的调用签名。

如果我将 type Props 中的子项明确指定为 any,则一切正常,但从 Typescript 和类型的角度来看,这是错误

当传递返回 React.ReactNode 的函数而不是 React.ReactNode 本身时,为 props.children 放置的正确类型是什么,因此 Typescript 会接受它作为有效的“渲染函数”并允许调用 @987654332 @like 函数?

【问题讨论】:

    标签: reactjs typescript children


    【解决方案1】:

    您可以将子类型指定为返回 ReactNode 的函数

    type Props = {
      id: string,
      children: (props: InjectedCounterProps) => React.ReactNode
    };
    

    【讨论】:

      【解决方案2】:

      JSX.Element 也可以是类型,以防子级为“DOM 元素”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-03
        • 1970-01-01
        • 1970-01-01
        • 2018-03-09
        • 1970-01-01
        • 1970-01-01
        • 2013-02-12
        相关资源
        最近更新 更多