英文:
How to inject prop types into component that is wrapped by hoc
问题
以下是您要翻译的内容:
我有一个类似这样的`HOC`
```jsx
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: T) {
const [windowSize, setWindowSize] = useState({} as WindowSize)
useEffect(() => {
// ...
}, [])
return <Component
{...props}
windowSize={windowSize}/>;
}
}
export default WithWindowSize;
现在我想使用这个HOC
。
interface FooProps {
headline: string,
value: string | number,
}
const Foo = ({headline, value, windowSize}: FooProps & WindowSize) => {
return ...
}
export default WithWindowSize(Foo);
这会给我报错
属性'windowSize'在类型'FooProps & WindowSize'上不存在。
我如何将属性类型WindowSize
注入到Foo
中?我认为最好的方法是在HOC
中执行,这样每次使用WithWindowSize
时都不必重复操作。
<details>
<summary>英文:</summary>
I have a `HOC` like this
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: T) {
const [windowSize, setWindowSize] = useState({} as WindowSize)
useEffect(() => {
...
}, [])
return <Component
{...props}
windowSize={windowSize}/>
}
}
export default WithWindowSize;
Now I want to use this `HOC`.
interface FooProps {
headline: string,
value: string | number,
}
const Foo = ({headline, value, windowSize}: FoooProps & WindowSize) => {
return ...
}
export default WithWindowSize(Foo);
This gives me
> Property 'windowSize' does not exist on type 'FooProps & WindowSize'.
How would I inject the prop type `WindowSize` into `Foo`? I would think the best way is to do it in the `HOC`, so that I do not have to do it every time I wrap something with `WithWindowSize`.
</details>
# 答案1
**得分**: 0
我会将`windowSize`作为`FooProps`接口的可选属性进行包含,因为无法让`Foo`(或任何其他组件)知道它将在HOC内部使用。
```typescript
interface WindowSize {
width: number,
height: number
}
interface FooProps {
headline: string,
value: string | number,
windowSize?: WindowSize
}
const Foo = ({ headline, value, windowSize }: FooProps) => {
return ...
}
英文:
I would just include the windowSize
as an optional property in the FooProps
interface, because there is no way for Foo
(or any other component) to know that it is going to be used within a HOC
interface WindowSize {
width: number,
height: number
}
interface FooProps {
headline: string,
value: string | number,
windowSize?: WindowSize
}
const Foo = ({headline, value, windowSize}: FooProps) => {
return ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论