gpt4 book ai didi

javascript - useRef typescript 错误 : Property 'current' does not exist on type 'HTMLElement'

转载 作者:行者123 更新时间:2023-12-05 00:24:54 27 4
gpt4 key购买 nike

我正在用 React 和 Typescript 制作一个 Datepicker,我似乎无法克服 useRef 的错误。和裁判的.current属性(property)。我正在尝试获取 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,如果这有帮助的话。

最佳答案

useRef不返回 ref 中的值 - 将返回值键入为 HTMLElement | null不准确。请改用通用参数:

const picker = React.useRef<HTMLElement>(null);
您还需要更改 toggle以便根据需要进行类型缩小:
const toggle = (e: MouseEvent) => {
const { current } = picker;
if (current && !current.contains(e.target)) {
setOpen(false);
}
}

关于javascript - useRef typescript 错误 : Property 'current' does not exist on type 'HTMLElement' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64508151/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com