GSAP Draggable 与 React ES6 actual this

GSAP Draggable with react ES6 actual this

我使用 gsap Draggable 和 reactjs ES6,我在 React 组件 componentDidUpdate 生命周期方法

中像这样创建新的 draggable
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 的内部方法主体应该给出当前元素,但它未定义并且 this 是错误的上下文。

如何在这个方法中访问当前的元素?

您正在使用 arrow function,它将自动 bind 将调用该方法的 object 的上下文。要访问目标元素,请使用 event object

In JavaScript, the thing called this, is the object that "owns" the JavaScript code. The value of this, when used in a function, is the object that "owns" the function.

这样写访问目标元素:

const draggable = Dragable.create('.box', {
   ...,
   onPress:(e) => {
     //now this.target is wrong
     const el = e.target;
   }
})

查看此答案以了解有关 this keyword 的更多详细信息。