【发布时间】: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