2017-05-31 91 views
0

林與reactjsES6,創建新的可拖動這樣在反應組分componentDidUpdate生命週期方法GSAP可拖動與反應ES6實際使用<code>gsap</code>可拖動的這個

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應該給當前元素但它的undefined和this是錯誤的上下文。

如何訪問此方法中的當前元素?

回答

1

您正在使用arrow function,它會自動bindobject將調用該方法的上下文。要訪問目標元素,請使用event object

在JavaScript中,稱爲this的事物是「擁有」 JavaScript代碼的對象。這個值在函數中使用時,是「擁有」該函數的對象。

寫這樣的訪問目標元素:

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

檢查這個答案爲更多細節this keyword

+0

非常感謝,它的工作。 –