Die*_*sel 4 typescript reactjs 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 问题,例如 this 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>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
这是发生错误的带有 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>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
您已经创建了两个组件Input, 和CustomInput。后者是使用 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} />}
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7693 次 |
| 最近记录: |