2017-07-08 33 views
0

我是React中的新成員,但我在JS中有一些經驗。如何使用mousOver獲得當前元素React

我的問題是:

我有一個功能,我把這個功能onmouseover事件到元素

<td> in current situation. 

我想這個當前的DOM元素,並得到下一個該元素的索引。

我的代碼是波紋管:

var Cell = function(k) { 
 

 

 
\t \t function getIndex(cell){ 
 
\t \t \t console.log(cell) 
 
\t \t } 
 

 

 

 
\t \t return (
 
\t \t \t <td key ={k} onMouseOver={function() {getIndex(this)}}> 
 
\t \t \t \t <div className="square__cell" ></div> 
 
\t \t \t </td> 
 
\t \t) 
 
\t 
 
}

在JS它的工作原理是這樣的。但是現在在React中它返回null。

如果我把console.log「1」例如它也可以。所以功能是炒鍋,我只有問題獲得有關當前元素的信息

請幫助瞭解如何做到這一點。 謝謝。

回答

-1
You have to bind the function instead of creating new function so the context scope of component remains same 

var Cell = function(k) { 
     function getIndex(cell){ 
      console.log(cell) 
     } 
     return (

      <td key ={k} onMouseOver={this.getIndex.bind(this,k)}}> 
       <div className="square__cell" ></div> 
      </td> 

     ) 
}