我使用 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/