【发布时间】: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