javascript - useRef Typescript 错误:“HTMLElement”类型上不存在属性“当前”
问题描述
我正在用 React 和 Typescript 制作一个 Datepicker,我似乎无法克服useRef
ref.current
属性的错误。当在文档之外单击文档时,我试图让div
我分配的 ref 关闭。
我只是似乎无法弄清楚我做错了什么。这是我的代码:
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);
}
}
推荐阅读
- opencv - 非图像基本结构中的 OpenCV 浮点数与双精度数
- vb.net - Visual basic .NET - 显示所选月份的天数
- go - 在银杏测试中检查非空值的正确方法
- java - 从 Firefox 74 / 75 发布 multipart/form-data 并在服务器端使用 Apache AJP 连接器时出现 java.io.IOException
- asp.net - 是否可以在 asp.net 上添加指向另一个页面的特定部分的链接?
- powershell - 批处理中的 Powershell:字符串到二进制并返回
- angular - 在动态创建的组件内动态创建组件
- android - 如何在我的 Android 清单文件中组织我的布局
- javascript - 发布时 Chrome 扩展后台脚本未运行
- microsoft-graph-api - 编辑实例时为系列主服务器发送图表日历更改通知