javascript - GSAP Draggable with React ES6 实际这个

标签 javascript reactjs this gsap

我使用 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 是错误的上下文。

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

最佳答案

您正在使用箭头函数,它会自动绑定(bind)对象的上下文,该对象将调用该方法。要访问目标元素,请使用事件对象

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 的更多详细信息

关于javascript - GSAP Draggable with React ES6 实际这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44280565/

相关文章:

javascript - 如何在 fabric.js 的 Canvas 上触发自定义事件?

reactjs - 如何默认为基于 URL 参数的路由

reactjs - 富文本编辑器光标不会移动,使文本向后输入

javascript - 在 Javascript(和 jQuery.extend)中限定 "this"

c# 下面构造函数中的两个 this 关键字有什么区别?

javascript - "This"未引用当前对象

javascript - 仅对字母和数字进行 jquery REGEX 验证

javascript - `serializeArray()` 未获取所有字段

javascript - 帮助使用 jQuery 获取元素

javascript - React textarea组件无法水平扩展