简体   繁体   中英

Accessing an object with dot notation using props

I'm trying to use React-DnD and I have this code:

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;

but the line

type: ItemTypes.{props.type}

doesn't work.

Constants.tsx

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

In the parent component, I want to decide which of those 4 options I want to pass onto the children, and then send through the props raspuns1/raspuns2/raspuns3/raspuns4.

In the above code you can see my approach - I also tried with bracket notation, but it hasn't worked either.

Is it possible to access the data in the object ItemTypes this way?

Thanks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM