【发布时间】:2021-11-08 04:15:26
【问题描述】:
我正在尝试将此类组件转换为函数组件,但我需要该组件具有这些静态属性。
export class InputBox<T extends string|number|undefined = undefined> extends React.Component<IInputBoxProps<T>, IInputBoxState> {
static displayName = "InputBox";
static defaultProps: IInputBoxProps<string|number> = {
disabled: false,
rightAligned: false,
id: "",
keySelectIndex: 0,
}
... rest of component
}
我试过这段代码:
export const InputBox: React.FunctionComponent<IInputBoxProps<any>> = <T extends string | number | undefined = undefined >(props: IInputBoxProps<T>) => {
InputBox.displayName = "InputBox";
InputBox.defaultProps = {
disabled: false,
rightAligned: false,
id: "",
keySelectIndex: 0,
}
... rest of component
}
当我运行这段代码时,我收到一个 eslint 错误提示:
FunctionComponent<IInputBox<any>>' is not a constructor function type.
T = any 在这里也不起作用。我知道any 有点让打字稿没用,但我似乎无法绕过这个错误。
如何使用“构造函数类型”键入函数组件,这究竟是什么意思?
类构造函数中的函数构造函数和类构造函数有什么区别? 我应该在函数组件中以不同的方式键入静态道具吗?
【问题讨论】:
-
我仍然收到 lint 错误。我也没有得到
defaultProps或displayName作为智能感知建议? -
@Kulio 你用的是什么版本的 TS? Aleksey 的示例在 4.4.4 中为我提供了智能感知建议
-
"typescript": "^4.4.4"
标签: reactjs typescript