reactjs - 定义对象时的打字稿对象属性
问题描述
我试图在创建对象期间推断对象属性。我有以下界面。
interface Config {
comp: ComponentType<any>;
props: any;
}
我可以成功创建配置。
const config: Config = {
comp: MyComponent;
props: {
prop1: 3,
prop2: "test"
}
};
我将如何强制 props 对象使用组件本身中定义的 props?
const config: Config[] = [
{
comp: MyComponent,
props: {
prop1: 3,
prop2: "test"
}
},
{
comp: AnotherComponent,
props: {
anotherProp: false
}
}
];
那么我将如何对数组强制执行相同的规则,其中每个配置都可以有不同的组件?
我尝试使用泛型并使用 infer 关键字,但很难让它工作。
谢谢。
编辑:
在最后一个示例中,我希望const config被键入为一个元组,看起来像这样:
[
{
comp: MyComponent,
props: ExtractPropsTypeOf<MyComponent>
},
{
comp: AnotherComponent,
props: ExtractPropsTypeOf<AnotherComponent>
}
]
解决方案
以下是 React 期望接收类型化 props 的示例:
export interface CaptionProps {
children: string;
}
export interface CaptionState {
}
export default class Caption extends React.Component<CaptionProps, CaptionState> {
constructor(props: Readonly<CaptionProps>) {
super(props);
}
render(): React.ReactNode {
return <div className="caption">{ this.props.children }</div>;
}
}
如果你像这样声明你的组件,你应该能够使用这个语法:
interface Config<Props> {
comp: React.Component<Props, any>;
props: Props;
}
推荐阅读
- java - 库使用尚未在 Android 中实现的方法
- flutter - 在颤动中显示来自后端的数据时获取 Null 或 Blank
- python - 从 python 文件创建可执行文件和 msi 并将其下载为工件使其显示为恶意软件
- javascript - 无法导入 TailwindCSS
- nestjs - 如何在nestJS中创建一个先调用的服务?
- django - 如何只运行一次 django 信号以影响多个模型实例
- awk - awk 将字符串拆分为单词和数字
- ios - 通过向下滑动来反应本机模式关闭(react-native-swipe-gestures)
- web - 在 Windows CMD 上使用“ping”命令,但数据包丢失
- python - ylabel 轴值 1e6 变化