React HoC与Typescript的使用



我有一个react HoC,其中我定义了几个状态,并将其传递给包装组件。但是被包装的组件本身有一些道具。

HoC.tsx

const HOC = (Component: React.ComponentType<T>) => {
const [someState, setSomeState] = useState()
const WrappedComponent = (props: T) =>
return(
<Component {(...props) as T} someState={someState}/>
)
return WrappedComponent
}

在需要其他道具的组件中使用

interfae NewComponentProps {
x: number
}
const NewComponent: React.FC<NewComponentProps> = (props) => {
let {x, someState} = props
//Here I am not able to access someState prop which is coming from HOC, typescript is giving error
return ( ... )
}
export default HoC(NewComponent)

如何处理这种情况,如果我在NewComponentProps接口中添加someState,它将工作但是当我在任何地方调用NewComponent时,我必须传递someState prop

那么要访问这两个道具,新组件的props类型应该是什么??

下面是一个小示例,说明如何输入它使其工作

type WrappedProps = {
b: string;
};
// Here you type the child component as generic T combined with 
// your Wrapped props
const Wrapped = <T,>(Comp: ComponentType<T & WrappedProps>) => {
return (props: T) => {
return <Comp {...props} b="World" />;
};
};
// ============================
type CompProps = {
a: string;
};
// You need to manually pass the props of your component to the Wrapped
// function, because it can't infer the type
const Comp = Wrapped<CompProps>((props) => {
// props now has the type CompProps & WrappedProps
return (
<p>
A: {props.a}
<br />
B: {props.b}
</p>
);
});
// ============================
export default function App() {
return <Comp a="Hello" />;
}

相关内容

  • 没有找到相关文章

最新更新