You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-DnD中通过props动态访问ItemTypes对象属性失败如何解决

问题原因

  1. 你最初写的 ItemTypes.{props.type} 不符合JS/TS语法规范,不能通过点运算符加花括号的方式访问对象的动态属性,必须使用方括号语法。
  2. 你之前尝试用方括号不生效的核心原因是TypeScript类型不匹配:你定义的type属性是通用string类型,但ItemTypes的键只有raspuns1/raspuns2/raspuns3/raspuns4四个固定值,TS会认为任意字符串不能保证是ItemTypes的合法键,因此会抛出类型错误。

修复方案

第一步:调整子组件类型定义与属性访问写法

将type的类型从string替换为keyof typeof ItemTypes,限定传入的值只能是ItemTypes中存在的键,再用方括号访问动态属性即可:

import { useDrag } from "react-dnd";
import { ItemTypes } from "./Constants";

// 修改type的类型,限定只能传入ItemTypes的合法键
type DraggableGameAnswerProps = {
    type: keyof typeof ItemTypes
}

function DraggableGameAnswer(props: DraggableGameAnswerProps)
{
    const [{ isDragging }, drag] = useDrag(() => ({
        // 用方括号访问动态属性
        type: ItemTypes[props.type],
        collect: (monitor) => ({
          isDragging: !!monitor.isDragging()
        })
      }))
    // 注意要将drag ref绑定到可拖拽的DOM元素上,原代码漏了返回渲染内容
    return <div ref={drag}>拖拽项内容</div>
}

export default DraggableGameAnswer;

第二步:父组件传值适配

父组件传入type参数时,只能传raspuns1/raspuns2/raspuns3/raspuns4四个值,TS会提前做类型校验避免运行时问题。
如果你的type值是动态获取的字符串,可以在传入前加一层类型断言:

<DraggableGameAnswer type={动态字符串变量 as keyof typeof ItemTypes} />

内容的提问来源于stack exchange,提问作者Octavian Niculescu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:36:07