使用临时样式组件转发 ref

Forwarding ref with hoc styled components

我想将 forwardRef 用于此组件,但无法正常工作。这是组件

import { StyledInput, StyledSecondaryInput } from './style'

const handleWrapping = (Component, props) => {
  const { ...rest } = props

  return <Component {...rest} />
}

export const Input = (props) => handleWrapping(StyledInput, props)

export const SecondaryInput = (props) =>
  handleWrapping(StyledSecondaryInput, props)

函数的第二个参数将是 ref,如果它被包裹在 forwardRef.

import { StyledInput, StyledSecondaryInput } from "./style";
import { forwardRef } from "react";

const handleWrapping = (Component, props) => {
  const { forwardedRef, ...rest } = props;

  return <Component {...rest} ref={forwardedRef} />;
};

export const Input = forwardRef((props, ref) =>
  handleWrapping(StyledInput, { forwardedRef: ref, ...props })
);

export const SecondaryInput = forwardRef((props, ref) =>
  handleWrapping(StyledSecondaryInput, { forwardedRef: ref, ...props })
);