Я пытаюсь написать функцию HOC для React Context, чтобы я мог обернуть другие компоненты с помощью Context, позволяя мне отправлять все уведомления одному компоненту. Мне пришлось собрать воедино рабочее решение из нескольких разных руководств, в основном , этого , поскольку ни одно из них не работало в первоначальном виде.
То, что я закончил, примерно так:
СПЕЦИАЛЬНЫЙ:
import * as React from "react";
import { INotificationContextState, NotificationConsumer } from "./NotificationContext";
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export default function withNotificationContext<
P extends { notificationContext?: INotificationContextState },
R = Omit<P, 'notificationContext'>
>(
Component: React.ComponentClass<P> | React.StatelessComponent<P>
): React.SFC<R> {
return function BoundComponent(props: R) {
return (
<NotificationConsumer>
{value => <Component {...props} notificationContext={value} />}
</NotificationConsumer>
);
};
}
Контекст:
interface IMessage {
message: string;
key: number;
}
interface INotificationState {
open: boolean;
messageInfo: IMessage;
timeOut: number;
}
interface INotificationContextState extends INotificationState {
handleClick(message: string): void;
handleClose(event: React.MouseEvent<HTMLElement>, reason: any): void;
handleExited(): void;
}
const NotificationContext = React.createContext<INotificationContextState | null>(
null
);
class NotificationProvider extends React.Component {
public state: Readonly<INotificationState> = DEFAULT_STATE;
private queue: IMessage[] = [];
constructor(props: INotificationContextState) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.handleClose = this.handleClose.bind(this);
}
// rest of the class methods...
}
export const NotificationConsumer = NotificationContext.Consumer;
Файл HOC дает мне красное подчеркивание под словом Component
в строке {value => <Component {...props} notificationContext={value} />}
Ошибка гласит:
Введите 'R & {tificationContext: INotificationContextState | ноль; } 'нельзя присвоить типу' IntrinsicAttributes & P & {children ?: ReactNode; }».
Тип 'R & {messagesContext: INotificationContextState | ноль; } 'нельзя назначить типу' P'.ts (2322)
Странно то, что эта ошибка не мешает мне запускать приложение, и, кроме того, функция-обертка работает точно так же, как и должна, а обернутый компонент может передавать уведомления объекту уведомления.
Часть моей проблемы в том, что я незнаком с синтаксисом Omit / Pick и пытаюсь мысленно понять, что именно является определением типа «P» в этом контексте. Я просто понятия не имею, почему он генерирует ошибку, но все еще работает.