【问题标题】:How do you declare the types for a component that uses set function?如何为使用 set 函数的组件声明类型?
【发布时间】:2021-09-19 22:39:56
【问题描述】:

这个例子运行良好,但类型还不能很好地编译它。

我有以下:

function SpotlightElement(props: JSX.IntrinsicElements['spotLight']) {
  return (
    <group ref={group}>
      <SpotLight ref={**set**} />
    </group>
  )
}

export default function MovingSpot() {
  const [depthBuffer, setDepth] = useState()
  return (
    <>
      <DepthBuffer ref={setDepth} size={512} />
      <SpotlightElement **depthBuffer**={depthBuffer} />
    </>
  )
}

这是我的疑问...如何让 typescript 理解 SpotLight 组件的 ref 是从 set 函数中检索的?截至目前,它假设是带来组件本身而不是配置它的功能:类型'Dispatch'不可分配给类型'Ref |未定义'。

另外,如果 SpotLightElement 函数中的 props 属性被声明为来自 'group' 的 JSX.IntrinsicElements ,这将是正确的类型,因为现在 depthBuffer 属性显然没有存在于三个types.d.ts中定义的spotLight props中:

类型“IntrinsicAttributes & Omit, NonFunctionKeys void)| ... 1 更多 ... |不明确的; }>> & { ...; } & EventHandlers'。

任何帮助将不胜感激。谢谢!!!

【问题讨论】:

  • 您能创建一个沙盒来展示您的问题吗?
  • :THREE.SpotLight ?

标签: typescript three.js react-three-fiber


【解决方案1】:

感谢您的回答。在 drei 背后的团队的建议下,我确实使用了 THREE.SpotLight。除了添加 SpotLightProps 类型外,我还必须更改三个提供的组件,这是最后一块:

type SpotLightProps = JSX.IntrinsicElements['spotLight'] & {
  depthBuffer?: DepthTexture
  attenuation?: number
  anglePower?: number
  color?: string | number
}

const vec = new Vector3()
function SpotlightElement(props: SpotLightProps, ref: React.ForwardedRef<SpotLightImpl>) {
  const group = useRef<THREE.Group>(null!)
  const [light, set] = useState<THREE.SpotLight>(null!)
  const viewport = useThree((state) => state.viewport)
  useFrame((state) => {
    group.current.position.lerp(vec.set(state.mouse.x, state.mouse.y, 0), 0.1)
    light.target.position.lerp(vec.set((state.mouse.x * viewport.width) / 2, (state.mouse.y * viewport.height) / 2, 0), 0.1)
  })
  return (
    <group ref={group}>
      <spotLight ref={set} />
      {light && <primitive object={light.target} />}
    </group>
  )
}

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 2019-02-03
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    相关资源
    最近更新 更多