繁体   English   中英

React HoC usage with Typescript

[英]React HoC usage with Typescript

I have a react HoC where I have define few states and I am passing that to wrapped component. But the wrapped component itself has some props.

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
}

Hoc Usage in a component which needs other props

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)

How to handle such case and if I add someState in NewComponentProps interface it will work but I have to pass someState prop when I will call the NewComponent anywhere

So what should be the props type of new component to access both 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" />; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM