首页 > 解决方案 > Apollo 客户端使用 hoc 和 TypeScript 访问组件道具

问题描述

打破我的头,我无法弄清楚如何通过 HOC 使用 typescript 实现突变并获得给予组件的道具。例如,我想要表单的“部分”名称,但在下面给出的示例中,我收到一个错误

type FormCollectionProps = {
   mutate: any;
   section: string;
}
type FormCollectionOnSortProps = {
   oldIndex: number;
   newIndex: number;
}

const withSectionData = graphql<{}, {}, {}, FormCollectionProps>(MOVE_COLLECTION_ITEM);
const FormCollection = ({ mutate, section }: FormCollectionProps, {}) => {

   const onSortEnd = ({ oldIndex, newIndex }: FormCollectionOnSortProps) => {
      console.log('oldIndex => ', oldIndex);
      console.log('newIndex => ', newIndex);
   }

   return (
      <Query query={GET_COLLECTION_ITEMS}>
         {({ data: {{ items }}, loading, error }) => (
            <CollectionItems items={items} section={section} onSortEnd={onSortEnd} />
         )}
      </Query>
   );
};

export default withSectionData(FormCollection);

执行

{formSections.map((section: string) => (
  <FormCollection key={section} section={section} />
))}

错误

Type error: Type '{ key: string; section: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, any, any>> & Readonly<{ children?: ReactNode; }>'.
  Property 'section' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<{}, any, any>> & Readonly<{ children?: ReactNode; }>'.  TS2322

因此,“FormCollection”集合组件不接受我提供的“section”道具。我怎样才能访问这个属性?

标签: reactjstypescriptreact-apollo

解决方案


答案;

type FormCollectionProps = {
   mutate?: any;
   section: string
}

type FormCollectionOnSort = {
   oldIndex: number;
   newIndex: number;
}

const withSectionData = graphql<FormCollectionProps, {}, {}, {}>(MOVE_RESUME_COLLECTION_ITEM);

我们必须为手动添加的组件属性插入“类型”作为 'graphql' hoc 的第一个参数。这解决了这个问题。


推荐阅读