使用泛型打字稿将道具连接到React类组件中的状态

时间:2020-06-26 16:53:35

标签: javascript reactjs typescript

我有办法让状态类型取决于传入的道具类型吗?

type FooProps = {
  allItems: any[]
}
type FooState = {
  items: any[]
}
export default class Foo extends React.Component<FooProps, FooState> {

1 个答案:

答案 0 :(得分:2)

您尝试过吗?

interface FooProps<T> {
    allItems: T[]
}

interface FooState<T> {
    items: T[]
}

export default class Foo<T> extends React.Component<FooProps<T>, FooState<T>> {}