0

我编写功能性 HOC 以在组件中添加查询。HOC 必须接受功能和类组件。

我写了这段代码:

const LISTS_QUERY = gql`
    query List {
        list {
            id
            address
            name
        }
    }
`;
interface WithListQueryProps {
    listQueryResult: QueryResult<ListQuery>;
}
type WithList =
    <T extends WithListProps, S extends {}>(Component: React.FC<T> | React.ComponentClass<T, S>)
        => (props: any)
            => JSX.Element;
export const withList: WithList = (Component) => {
    return props => (
        <Query<ListQuery>
            query={LISTS_QUERY}
        >
            {listQueryResult => (
                <Component
                    {...props}
                    listQueryResult={listQueryResult}
                />
            )}
        </Query>
    );
};

这个 HOC 这么称呼:

interface Props {
    userName: string;
}

export const MenuConnect: React.FC<Props> = (props: Props) => {
    const MenuBehaviourWithList = withList(MenuBehaviour);
    return (
        <MenuBehaviourWithList {...props}/>
    );
};

HOC工作。我不喜欢any。需要将propsHOC 中的 WithList 类型从您的更改any为您的。

4

1 回答 1

0

在函数中写入类型。将调用交换为命令式。


export const withList = <P extends WithListProps, S extends {}>(
    Component: React.FC<P> | React.ComponentClass<P, S>,
) => {
    return (props: React.PropsWithChildren<Omit<P, 'listQueryResult'>>): JSX.Element => (
        <Query<GetListQuery, GetListQueryVariables> query={LIST_QUERY} >
            {listQueryResult => (
                React.createElement(Component, { ...props, listQueryResult } as P)
            )}
        </Query>
    );
};

于 2022-02-02T08:14:06.660 回答