首页 > 解决方案 > 使用 props 访问带有点符号的对象

问题描述

我正在尝试使用 React-DnD 并且我有以下代码:

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

type DraggableGameAnswerProps = {
    type: string
}

function DraggableGameAnswer(props: DraggableGameAnswerProps)
{
    const [{ isDragging }, drag] = useDrag(() => ({
        type: ItemTypes.{props.type},
        collect: (monitor) => ({
          isDragging: !!monitor.isDragging()
        })
      }))
}

export default DraggableGameAnswer;

但线

type: ItemTypes.{props.type}

不起作用。

常量.tsx

export const ItemTypes = {
    raspuns1: 'raspuns1',
    raspuns2: 'raspuns2',
    raspuns3: 'raspuns3',
    raspuns4: 'raspuns4'
}

在父组件中,我想决定将这 4 个选项中的哪一个传递给子组件,然后通过 props raspuns1/raspuns2/raspuns3/raspuns4 发送。

在上面的代码中,您可以看到我的方法 - 我也尝试使用括号表示法,但它也没有奏效。

是否可以通过这种方式访问​​对象 ItemTypes 中的数据?

谢谢。

标签: javascriptreactjstypescript

解决方案


我猜你在找:ItemTypes[prop.type]


推荐阅读