为onClick处理程序正确键入Apollo Mutation渲染道具

时间:2018-12-10 09:38:18

标签: reactjs typescript graphql apollo

我目前正在尝试用TypeScript重写HowToGraphQL教程,并创建了一个带有相应查询的自定义突变类,如下所示:

export const postMutation = gql`
    mutation PostMutation($description: String!, $url: String!) {
        post(description: $description, url: $url) {
            id
            createdAt
            url
            description
        }
    }
`;

export interface PostMutationData {
    post: {
        id: string;
        createdAt: string;
        url: string;
        description: string;
    };
}

export interface PostMutationVariables {
    description: string;
    url: string;
}

export class PostMutation extends Mutation<PostMutationData, PostMutationVariables> {}

消耗突变的成分基本上是这样的:

<PostMutation mutation={postMutation} variables={{ description, url }}>
    {(onMutate) => <button onClick={onMutate}>Submit</button>}
</PostMutation>

不幸的是,编译器抱怨并说我无法将onMutate分配给onClick并显示以下错误消息:

Type 'MutationFn<PostMutationData, PostMutationVariables>' is not assignable to type '(event: MouseEvent<HTMLButtonElement>) => void'.
    Types of parameters 'options' and 'event' are incompatible.
        Type 'MouseEvent<HTMLButtonElement>' has no properties in common with type 'MutationOptions<PostMutationData, PostMutationVariables>'.

我想知道如何正确地将onMutate处理程序分配给onClick

1 个答案:

答案 0 :(得分:0)

onMutate函数期望将名为“ options”的对象参数作为其第一个参数。您正在尝试将其分配给onClick,它的第一个参数是事件类型,这使类型不兼容。

有几种方法可以解决此问题。您可以创建一个在声明按钮之前使用option参数调用onMutate的函数,然后将该函数简单地传递给onClick。

<PostMutation mutation={postMutation}>
    {(onMutate) => {
        const onMutateFunc = () => onMutate({ variables: { description, url } })
        return (
            <button onClick={onMutateFunc}>Submit</button>}
        )
     }
</PostMutation>

或者您可以创建一个调用onMutate的onClick函数。

// Class level function
onClick = () => onMutate({ variables: { description, url } })

<PostMutation mutation={postMutation}>
    {(onMutate) => {
        const onMutateFunc = onMutate({ variables: { description, url } })
        return (
            <button onClick={this.onClick}>Submit</button>}
        )
    }
</PostMutation>

您也可以直接内联

<PostMutation mutation={postMutation}>
    {(onMutate) => {
        return (
            <button onClick={() => onMutate({ variables: { description, url } })}>Submit</button>}
        )
    }
</PostMutation>