jor*_*mer 7 javascript typescript reactjs visual-studio-code react-hooks
我正在用 React 和 Typescript 制作一个 Datepicker,我似乎无法克服useRefref 和 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" : "")}
>
//...
)
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
.current 给了我以下内容:
Property 'current' does not exist on type 'HTMLElement'.
Run Code Online (Sandbox Code Playgroud)
当我尝试将 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>'
Run Code Online (Sandbox Code Playgroud)
我使用 VSCode 作为我的 IDE,如果这有帮助的话。
Cer*_*nce 11
useRef不返回 ref 中的值 - 键入返回值HTMLElement | null是不准确的。改用泛型参数:
const picker = React.useRef<HTMLElement>(null);
Run Code Online (Sandbox Code Playgroud)
您还需要进行更改,toggle以便根据需要进行类型缩小:
const toggle = (e: MouseEvent) => {
const { current } = picker;
if (current && !current.contains(e.target)) {
setOpen(false);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9347 次 |
| 最近记录: |