【发布时间】:2021-10-01 03:28:07
【问题描述】:
对于反应组件的传递类型,我无法弄清楚。
父组件:
import React from "react";
import ChildrenComponent from './ChildrenComponent'
type TParentComponent = {
// no matter what here
}
const ParentComponent:React.FC<TParentComponent> = props => {
type TTypeInParentComponent = 'special type I can declare only inside ParentComponent'
type TChildrenComponent = {
childrenComponentProp: TTypeInParentComponent
}
return (
<ChildrenComponent<TChildrenComponent> /* error: TS2558: Expected 0 type arguments, but got 1. */>
Something
</ChildrenComponent>
)
}
export default ParentComponent
子组件:
import React from "react";
type TChildren = {
// how to pass the "TChildrenComponent" type from the ParentComponent here?
}
const ChildrenComponent:React.FC<TChildren> = props => {
const { childrenComponentProp } = props /* error: TS2339: Property 'childrenComponentProp' does not exist on type '{ children?: ReactNode; }'. */
return (
<div>
Something else
</div>
)
}
export default ChildrenComponent
问题:如何将类型 TChildrenComponent 从 ParentComponent 传递给 ChildrenComponent ?
一段时间后,我仍然没有找到我的问题的答案。但我想在这里留下一些解释。
例子:
const ParentComponent = () => {
// yes, exactly INSIDE the component. not ouside with "export type ..."
type TChildrenComponentSpecialType = string
return (
// ↓↓↓ here we pass the type to children component
<ChildrenComponent<TChildrenComponentSpecialType>
specialParam='no matter what'
/>
);
};
这就是我们如何使用像“function Component() {}”这样的简单函数声明的组件
// ↓↓↓ here we get it ↓↓↓ here we pass it to children component's type
function ChildrenComponent<T>(props: TChildrenComponentProps<T>):JSX.Element {
const { specialParam } = props;
return (
<div>no matter what is here</div>
);
};
但是我还没有找到如何用箭头函数声明的组件来做到这一点。 我们不能这样做:
const ChildrenComponent = <T>(props: TChildrenComponentProps<T>):JSX.Element => {
const { specialParam } = props;
return (
<div>no matter what is here</div>
);
};
【问题讨论】:
-
您的
TChildren类型不是通用的。它应该被定义为type TChildren<MyGeneric> = { arg: MyGeneric[] }。 -
@Noah May,问题不在这里。我知道如何传递给类型。问题不在于它。
标签: reactjs typescript generics