我使用的是相当严格的 TS 和 ESLint 版本。
我从此处的文档中删除了此门户:https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/portals/
我将代码修改为以下内容:
import React, { useEffect, useRef, ReactNode } from 'react'
import { createPortal } from 'react-dom'
interface Props {
children?: ReactNode
portalId: string
}
export const Portal: React.FC<Props> = ({ children, portalId }) => {
const el = useRef(document.createElement('div'))
useEffect(() => {
const portalRoot = document.querySelector(`#${portalId}`) as HTMLElement
const current = el.current
portalRoot.appendChild(current)
return () => void portalRoot?.removeChild(current) // error thrown here?
}, [portalId])
return createPortal(children, el.current)
}
以下错误:
Expected 'undefined' and instead saw 'void'
当我删除void
(不能使用undefined
,否则其余代码无法访问)时,如下所示:
import React, { useEffect, useRef, ReactNode } from 'react'
import { createPortal } from 'react-dom'
interface Props {
children?: ReactNode
portalId: string
}
export const Portal: React.FC<Props> = ({ children, portalId }) => {
const el = useRef(document.createElement('div'))
useEffect(() => {
const portalRoot = document.querySelector(`#${portalId}`) as HTMLElement
const current = el.current
portalRoot.appendChild(current)
return () => portalRoot?.removeChild(current) // how to fix?
}, [portalId])
return createPortal(children, el.current)
}
这会导致另一个错误:
Argument of type '() => () => HTMLDivElement' is not assignable to parameter of type 'EffectCallback'.
Type '() => HTMLDivElement' is not assignable to type 'void | Destructor'.
Type '() => HTMLDivElement' is not assignable to type 'Destructor'.
Type 'HTMLDivElement' is not assignable to type 'void | { [UNDEFINED_VOID_ONLY]: never; }'
如何解决?
最佳答案
这只是意味着“析构函数”(即从 useEffect
返回的清理函数)应该不返回任何内容。
但是由于你使用了箭头函数short form ,其结果会自动返回。例如,只需用大括号将其括起来以防止自动返回:
return () => {
portalRoot?.removeChild(current)
}
关于javascript - React TypeScript Cheatsheet 的门户示例代码似乎已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73821747/