代码之家  ›  专栏  ›  技术社区  ›  four-eyes

通过高阶组件注入道具会导致编译器错误

  •  1
  • four-eyes  · 技术社区  · 3 年前

    我正在尝试使用更高阶的组件(hoc)将道具注入到组件中。我顺着这个走 article 。这是我的即席:

    // WithWindowSize.tsx
    import React, {useEffect, useMemo, useState} from 'react'
    
    interface WindowSize {
        width: number,
        height: number
    }
    
    export function WithWindowSize <T>(Component: React.ComponentType<T>) {
        return function WithComponent(props: Omit<T, "width" | "height">) {
            const [windowSize, setWindowSize] = useState({} as WindowSize)
    
            useEffect(() => {
                ...
            }, [])
    
    
            return <Component
                {...(props as T)}
                windowSize={windowSize}/>
        }
    }
    
    export default WithWindowSize;
    

    这就是我尝试使用hoc的方式 WithWindowSize

    // Foo.tsx
    interface FooProps {
        headline: string,
        value: string | number,
    }
    
    const Foo = ({headline, value, windowSize}: FooProps) => {
        return ...
    }
    
    export default WithWindowSize(Foo);
    

    但是,这突出了 prop windowSize 在里面 <Foo /> ,告诉我

    类型“FooProps”上不存在属性“windowSize”。

    为什么?

    1 回复  |  直到 3 年前
        1
  •  3
  •   avani kothari    3 年前

    定义 windowSize 您定义的接口中的道具

    interface FooProps {
        headline: string,
        value: string | number,
        windowSize: string | number
    }
    

    我还看到类型中有一个额外的O FoooProps 你给出的是打字错误还是其他类型 FooProps ?

    推荐文章