簡體   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