Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React withProps #45

Open
varHarrie opened this issue May 20, 2022 · 0 comments
Open

React withProps #45

varHarrie opened this issue May 20, 2022 · 0 comments
Labels
Milestone

Comments

@varHarrie
Copy link
Owner

varHarrie commented May 20, 2022

实现withProps函数,用于提前注入组件属性。

import { ComponentProps, ComponentType, ForwardRefExoticComponent, forwardRef, memo } from 'react';

type ElementType = keyof JSX.IntrinsicElements | ComponentType;

type GetProps<C extends ElementType, E> =
  | Partial<ComponentProps<C>>
  | ((props: ComponentProps<C> & E) => Partial<ComponentProps<C>>);

export function withProps<C extends ElementType>(
  Component: C,
): <EP = {}>(getProps: GetProps<C, EP>) => ForwardRefExoticComponent<ComponentProps<C> & EP> {
  const Comp = Component as any; // Fixed "Expression produces a union type that is too complex to represent."

  return (getProps) => {
    return memo(
      forwardRef((props: any, ref) => {
        const injectedProps = typeof getProps === 'function' ? getProps(props) : getProps;
        return <Comp ref={ref} {...props} {...injectedProps} />;
      }),
    );
  };
}

示例:

import { CSSProperties } from 'react';

type InputProps = {
  type?: 'text' | 'password' | 'file';
  value?: string;
  style?: CSSProperties;
};

function Input(props: InputProps) {
  return <input {...props} />;
}

const PasswordInput = withProps(Input)({ type: 'password' });
// const PasswordInput = withProps('input')({ type: 'password' });

const CustomInput = withProps(Input)<{ block?: boolean }>((props) => ({
  style: props.block ? { display: 'block' } : undefined,
}));

const password = <PasswordInput value='123456' />

const custom = <CustomInput block value='hello' />
@varHarrie varHarrie added this to the Snippets milestone May 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant