函数组件的警告不能被赋予 refs - 即使将 forwardRef() 与 Styled Components 一起使用

Warning with function components cannot be given refs - even though using forwardRef() with Styled Components

我收到警告 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?。我很困惑,因为我正在使用 forwardRef()...而且它正在工作。

我正在尝试将我的自定义输入元素传递给 ReactDatePicker。有几个 GitHub 问题,例如这个 one。但是我无法解决最后一个错误,同时在其中实施有效的示例。

这是自定义 Input 元素:

interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
  ref?: React.Ref<HTMLInputElement>;
}

const StyledInput = styled.input<InputProps>`
  box-sizing: border-box;
  // ...
`;

export const Input: FunctionComponent<InputProps> = (props: InputProps) => {
  return (
    <>
      <StyledInput {...props}></StyledInput>
    </>
  );
};

这里是自定义的DatePicker和ReactDatePicker发生错误的地方:

interface DatePickerProps extends ReactDatePickerProps {
    //... custom props
}

const StyledDatePicker = styled(ReactDatePicker)`
    //... some CSS
`;

const CustomInput = forwardRef<HTMLInputElement>((inputProps, ref) => (
  <Input {...inputProps} ref={ref} /> // <-- error occurs here
));

export const DatePicker: FunctionComponent<DatePickerProps> = (props: DatePickerProps) => {
  const ref = React.createRef<HTMLInputElement>();

  return (
    <>
      <StyledDatePicker
        {...props}
        customInput={<CustomInput ref={ref} />}
      ></StyledDatePicker>
    </>
  );
};

您已经创建了两个组件,InputCustomInput。后者是使用 forwardRef 实现的,因此您可以将 ref 传递给它。前者不是,因此将 ref 传递给它是错误的。在我看来,CustomInput 没有任何作用,所以我认为您的意思是只有一个组件,它使用 forwardRef:

export const Input = React.forwardRef((props: InputProps, ref: React.Ref<HtmlInputElement>) => {
  return (
    <>
      <StyledInput {...props} ref={ref}/>
    </>
  )
});

// To be used like:
<StyledDatePicker
  {...props}
  customInput={<Input ref={ref} />}
/>

我所做的只是简单地使用 non-React 名称作为 ref 属性,re-map 将其 ref在 then 组件内部。我喜欢使用 xref 所以每当我在代码中看到它时,我就知道它的确切用途:

const CustomInput = (inputProps, xref) => (
  <Input {...inputProps} ref={xref} /> // <-- error occurs here, no more!
)

  return (
    <>
      <StyledDatePicker
        {...props}
        customInput={<CustomInput xref={ref} />}
      ></StyledDatePicker>
    </>
  )
}