我有一个React-Final-Form,我希望它使用自己的类型来键入。 但是`children(renderRest)'给出以下错误:
无法调用类型缺少调用签名的表达式。类型 '字符串|编号真实| {} | ReactElement ReactElement 组件)> | null)| (新(道具:任意)=> 组件)> | ReactNodeArray | ReactPortal | ((道具: FormRenderProps)=> ReactNode)'没有兼容的调用 signatures.ts(2349)
我的代码是:
import React from "react";
import styled from "styled-components";
import { Form as StateForm, FormProps } from "react-final-form";
import Box from "src/App/Components/Layout/Box";
const StyledForm = styled(Box)``;
const Form = ({ children, ...rest }: FormProps) => {
return (
<StateForm
{...rest}
render={({ handleSubmit, ...renderRest }) => (
<StyledForm as="form" onSubmit={handleSubmit}>
{children && children(renderRest)}
</StyledForm>
)}
/>
);
};
export default React.memo(Form);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
在我能够解决的各种情况下,发生了此错误“无法调用类型缺少呼叫签名的表达式”。但不幸的是,这种情况并非如此。
请问有什么提示吗?谢谢
答案 0 :(得分:0)
在react-final-form
的类型定义中,它在children
(RenderableProps
进行了扩展)中将FormProps
定义为:
export interface RenderableProps<T> {
children?: ((props: T) => React.ReactNode) | React.ReactNode;
component?: React.ComponentType<T> | string;
render?: (props: T) => React.ReactNode;
}
因此,children
是接受props
并创建React.ReactNode
的函数,或者它是直接React.ReactNode
的实例。在后一种情况下,您不能像函数一样使用它。由于可能是TS,TS只会让您执行两者之间的共同点。错误Cannot invoke an expression whose type lacks a call signature.
基本上是在说:“您正在尝试像使用children
一样是一个函数,但不允许这样做,因为我不确定它是否是一个函数。”
我对react-final-form
库的了解不够,无法说出解决此问题的最佳方法。你可以投...
(children as ((props: T) => React.ReactNode))(renderRest);
...或者您可以添加类型保护...
if (typeof children === 'function') {
children(renderRest);
}