【问题标题】:Warning with function components cannot be given refs - even though using forwardRef() with Styled Components函数组件的警告不能给出 refs - 即使将 forwardRef() 与 Styled Components 一起使用
【发布时间】:2020-02-22 17:42:08
【问题描述】:

我收到警告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>
    </>
  );
};

这是发生错误的带有 ReactDatePicker 的自定义 DatePicker:

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>
    </>
  );
};

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    您已经创建了两个组件,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} />}
    />
    

    【讨论】:

    • 谢谢,这很有帮助。对于我对Input 组件的所有用法,即使只有一个组件的实现使用ref,使用forwardRef 有什么负面影响吗?我没有看到为什么不这样做的原因。
    • 我能想到的没有什么负面的。
    【解决方案2】:

    我所做的只是使用一个 non-React 名称作为 ref 属性,然后将其重新映射到组件内部的 ref。我喜欢使用xref,所以每当我在代码中看到它时,我就知道它的用途:

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

    【讨论】:

    • 谢谢,这有助于清除我收到的警告。
    猜你喜欢
    • 2021-06-05
    • 2020-10-20
    • 1970-01-01
    • 2021-05-26
    • 2019-07-11
    • 2021-05-30
    • 2022-07-29
    • 2022-08-18
    • 2019-11-02
    相关资源
    最近更新 更多