首页 > 解决方案 > 正确输入 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" />;

标签: reactjstypescript

解决方案


我没有找到没有类型断言的方法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" />;

操场


推荐阅读