reactjs - 正确输入 prop injection
问题描述
我正在尝试将道具注入组件。我原以为这会起作用,并且在查看并尝试了多种配置之后,似乎没有任何东西可以使类型检查通过。看看其他答案,我猜我在做一些愚蠢的事情;但我看不出是什么。
我正在尝试在alerter
下面的示例中注入道具,但出现错误:
(参数) WrappedComponent: React.ComponentType Type '{ alerter: (s: string) => void; } & Pick<T, Exclude<keyof T, "alerter">>' 不可分配给类型 'IntrinsicAttributes & T & { children?: ReactNode; }'。键入'{警报器:(s:字符串)=> void;} & Pick<T, Exclude<keyof T, "alerter">>' 不可分配给类型 'T'。'{警报器:(s:字符串)=> void;} & Pick<T, Exclude<keyof T, "alerter">>' 可分配给“T”类型的约束,但“T”可以用约束“IWithAlert”的不同子类型实例化。ts(2322)
我已经多次看到“但是'T'可以用不同的约束子类型实例化”并且之前修复过它,但是在这里,我不明白为什么它甚至会首先发生。
有什么建议么?
import * as React from "react";
export interface IWithAlert {
alerter: (s: string) => void;
}
const withAlerter = <T extends IWithAlert = IWithAlert>(
WrappedComponent: React.ComponentType<T>
): React.ComponentType<Omit<T, "alerter">> => {
return class WithVisibilityControls extends React.Component<Omit<T, "alerter">> {
alerter = (s: string) => {
window.alert(s);
};
render() {
return <WrappedComponent alerter={this.alerter} {...(this.props as Omit<T, "alerter">)} />;
}
};
};
const Test: React.FC<{ alerter: (s: string) => void; m: string }> = (props) => {
return <button onClick={() => props.alerter(props.m)}>Click</button>;
};
const TestInjected = withAlerter(Test);
export default () => <TestInjected m="Hello" />;
解决方案
我没有找到没有类型断言的方法as
。
import React, { FC } from "react";
type IWithAlert = { alerter: (s: string) => void; m: string }
const withAlerter = <Props extends IWithAlert, T extends Props>(
WrappedComponent: FC<Props>
) => {
const alerter = (s: string) => {
window.alert(s);
};
const Foo: FC<Omit<T, 'alerter'>> = (props) => {
const prop = {
...props,
alerter
} as unknown as Props
return <WrappedComponent {...prop} />;
}
return Foo
};
const Test: React.FC<IWithAlert> = (props) => {
return <button onClick={() => props.alerter(props.m)}>Click</button>;
};
const TestInjected = withAlerter(Test);
const x = <TestInjected m="Hello" />;
推荐阅读
- bash - 如何将配置文件中的相同单词替换为数组中的不同单词
- python - 如何使用 boost.python 将字典列表从 C++ 返回到 python 而不会泄漏内存?
- objective-c - 以编程方式访问 AWS IAM 用户策略和访问
- apache-spark - SparkFiles.get() 方法无法找到,因为 Input Split 在末尾添加了字符串
- sql - 返回带有透视数据的多列
- python - 静态文件不起作用:未找到:/{static 'logo.png'}
- composer-php - 使用 bitbucket repo 和 composer deployer 进行部署时,我是否遗漏了什么?
- javascript - 解析平台 - 如何仅基于指针 a 进行查询
- c - 指向视频内存的指针有些奇怪(0xB8000)
- android - 如何正确覆盖 Resource 类以实现动态翻译系统?