作者:手机用户2502901265_642 | 来源:互联网 | 2022-12-09 21:39
问题:界面Stateless Functional Component
给出为
interface SFC {
(props: P & { children?: ReactNode }, context?: any): ReactElement | null;
propTypes?: ValidationMap;
}
我的组件的prop类型也是通用的:
interface Prop{
num: V;
}
如何正确定义我的组件?如:
const myCom: SFC> = (props: Prop)=> test
在给出了一个错误character 27
的是Cannot find name 'T'
这是:Modifiedcript Playground的修改示例
MyFindings:
1:Typescript 2.9.1支持有状态通用组件:http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#generic-type-arguments-in-jsx-elements
class myCom extends React.Component, any> {
render() {
return test
;
}
}
2:扩展SFC
以创建一个新接口,如下面的答案中所述,将使组件的prop类型为any
:
Typescript使用我不想要的泛型参数/返回类型的React无状态函数.我想为我的道具提供合适的类型
1> jmattheis..:
你不能使用这样的泛型:
const myCom: SFC> = (props: Prop)=> test
TypeScript规范说明:
形式的构造
( ... ) => { ... }
可以解析为箭头函数表达式,其类型参数或类型断言应用于没有类型参数的箭头函数.
资源; Microsoft/TypeScript spec.md
您的声明与TypeScript规范中定义的模式不匹配,因此它不起作用.
但是,您可以不使用SFC接口,只需自己声明.
interface Prop {
num: V;
}
// normal function
function Abc(props: Prop): React.ReactElement> {
return ;
}
// const lambda function
const Abc: (p: Prop) => React.ReactElement> = (props) => {
return
};
export default function App() {
return (
num={1} />
num="abc" />
num={1} /> // string expected but was number
);
}
2> 小智..:
有一种模式可以通过在组件外部声明通用组件类型别名,然后在需要时简单地声明它来缓解此问题。
虽然不那么漂亮,但是仍然可以重用和严格。
interface IMyComponentProps {
name: string
type: T
}
// instead of inline with component assignment
type MyComponentI = React.FC>
const MyComponent: MyCompOnentI= props => Hello
const TypedCompOnent= MyComponent as MyComponentI
3> chris..:
工厂模式:
import React, { SFC } from 'react';
export interface GridProps {
data: T[];
renderItem: (props: { item: T }) => React.ReactChild;
}
export const GridFactory = (): SFC> => () => {
return (
...
);
};
const Grid = GridFactory();