React Context HOC 関数を作成して、他のコンポーネントを Context でラップして、すべての通知を単一のコンポーネントに送信できるようにしようとしています。いくつかの異なるガイドから実用的なソリューションをつなぎ合わせる必要がありました。主にこれは、元の形式ではまったく機能しなかったためです。
私が最終的に得たのは次のようなものです:
HOC:
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 & { notificationContext: INotificationContextState | と入力します。ヌル; }' はタイプ 'IntrinsicAttributes & P & { children?: ReactNode; に割り当てられません。}'。'R & { notificationContext: INotificationContextState | と入力します。ヌル; }' は型 'P'.ts(2322) に代入できません
奇妙なことに、このエラーによってアプリの実行が妨げられることはありません。さらに、ラッパー関数は正常に機能し、ラップされたコンポーネントは Notification オブジェクトに通知を渡すことができます。
私の問題の一部は、Omit/Pick 構文に慣れておらず、このコンテキストで "P" の型定義が何であるかを頭の中で正確に理解しようとしていることです。エラーが発生する理由はわかりませんが、それでも機能します。