【问题标题】:Don't require props, when using component with HOC使用带有 HOC 的组件时不需要道具
【发布时间】:2021-06-01 03:36:06
【问题描述】:

我对 HOC 和打字稿有疑问。编译器需要传递从 HOC 接收的值。

正在使用 HOC 的组件:

function Coupon(props: WithAlertProps): JSX.Element {
 return <p>test {props.error}</p>
}
export default withAlert(Coupon);

HOC:

export interface WithAlertProps {
    error: string;
}

const withAlert = <P extends unknown>(
    Component: React.ComponentType<P>
): React.FC<P & WithAlertProps> => (props) => {
    return (
            <Component {...props} error={"sample error"} />
    );
};

export default withAlert;

当我尝试使用组件时,我收到消息:“{}”类型缺少“WithAlertProps”类型中的以下属性:错误

那么如何通知 typescript 它有来自 HOC 的错误值?

【问题讨论】:

  • 只需从函数返回类型中删除&amp; WithAlertProps
  • 它不会改变任何东西。还是一样的信息

标签: reactjs typescript


【解决方案1】:

您的类型未对齐。您的 withAlert hoc 接收带有 P &amp; WithAlertProps 道具的组件并返回接收 P 道具的组件。

const withAlert = <P extends unknown>(
    Component: React.ComponentType<P & WithAlertProps>
): React.FC<P> => (props) => {
    return (
        <Component {...props} error={"sample error"} />
    );
};

TS playground

【讨论】:

    猜你喜欢
    • 2020-07-30
    • 2018-07-23
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多