Javascript GSAP可与react ES6牵引

Javascript GSAP可与react ES6牵引,javascript,reactjs,this,gsap,Javascript,Reactjs,This,Gsap,我在react JS ES6中使用gsap Dragable,我在react component componentDidUpdate生命周期方法中创建了这样的新Dragable import React, { Component } from 'react' import Draggable from 'gsap/Draggable' class DraggableContainer extends Component { render(){ ... }

我在react JS ES6中使用gsap Dragable,我在react component componentDidUpdate生命周期方法中创建了这样的新Dragable

import React, { Component } from 'react'
import Draggable from 'gsap/Draggable'

class DraggableContainer extends Component {

    render(){
        ...
    }
    componentDidUpdate(){
        const draggable = Draggable.create('.box', {
            onPress: ()=>{
                // currentElement suppost to contain dom element of clicked, but its undefined because 'this' is 'DraggableContainer'
                const currentElement = this.target

            }   
        })
    }
}
在onPress this.target的方法体内部,应该给出当前元素,但其未定义,这是错误的上下文

如何访问此方法中的当前元素?

如果使用arrow函数,它将自动绑定调用该方法的对象的上下文。要访问目标元素,请使用事件对象

在JavaScript中,称为this的对象是拥有 JavaScript代码。当在函数中使用时,它的值是拥有该函数的对象

按如下方式编写以访问目标元素:

const draggable = Dragable.create('.box', {
   ...,
   onPress:(e) => {
     //now this.target is wrong
     const el = e.target;
   }
})
检查此答案以了解有关的更多详细信息