【发布时间】:2021-02-06 23:59:38
【问题描述】:
我正在使用 React 和 Typescript 制作一个 Datepicker,但我似乎无法克服 useRef 和 ref 的 .current 属性的错误。我正在尝试获取div,当在文档之外单击文档时,我将引用分配给关闭。
我似乎无法弄清楚我做错了什么。这是我的代码:
function Datepicker({label, placeholder}: DatepickerProps){
const [open, setOpen] = React.useState(false)
const [day, setDay] = React.useState(0)
const [month, setMonth] = React.useState(new Date().getMonth())
const [year, setYear] = React.useState(new Date().getFullYear())
const picker = React.useRef(null) as HTMLElement | null
React.useEffect(() => {
document.addEventListener("mousedown", toggle)
return () => {
document.removeEventListener("mousedown", toggle)
};
}, []);
const toggle = (e: MouseEvent) => {
if (picker && picker.current){
if (picker.current.contains(e.target) === false){
setOpen(false)
}
}
}
//...
return(
//...
<div
ref={picker}
className={"datepicker-picker" + (open ? " open" : "")}
>
//...
)
}
React.useRef(null) as HTMLElement | null 给我以下问题:
Conversion of type 'MutableRefObject<null>' to type 'HTMLElement' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type 'MutableRefObject<null>' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 234 more.ts(2352)
.current 给了我以下信息:
Property 'current' does not exist on type 'HTMLElement'.
当我尝试将 ref 应用于 div 元素时,它会显示以下内容:
Type 'HTMLElement | null' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
Type 'HTMLElement' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
Type 'HTMLElement' is not assignable to type 'string'.ts(2322)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'
我正在使用 VSCode 作为我的 IDE,如果这有帮助的话。
【问题讨论】:
标签: javascript reactjs typescript visual-studio-code react-hooks