javascript - React TypeScript Cheatsheet 的门户示例代码似乎已损坏

标签 javascript reactjs typescript

我使用的是相当严格的 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/

相关文章:

javascript - 为什么 Redux reducer 必须没有副作用?

javascript - Spring Boot 的 Whitelabel 错误错误页面

javascript - 在 ionic 4 中使用 .js 文件

Angular : Unable to build application

typescript - 从 Typescript 引用 DLL

javascript - jQuery Mosaic Flow,在我调整浏览器窗口大小之前图像不可见

javascript - 将上传的图片 url 传递给 javascript

javascript - 如何从具有一个或多个类名的元素中查找恰好具有特定且唯一的类名(而不是任何其他类名)的元素?

javascript - 在 Rails 中测试 JavaScript View

reactjs - Material-ui 覆盖 react 情感规则