2016-11-15 62 views
0

所以我有這個代碼在這裏,我基本上試圖隱藏一些圖標,當我把鼠標懸停在它的父div上。或使其可見,但無論哪種方式...(React)懸停時不能隱藏內容?

export class ProgramDescription extends React.Component { 

    constructor(props) { 
    super(props); 
    } 

    showIcon() { 
    this.refs.edit.style.visibility = 'visible'; 
    }; 

    hideIcon() { 
    this.refs.edit.style.visibility = 'hidden'; 
    }; 

    componentDidMount() { 
    this.refs.edit.style.visibility = 'hidden'; 
    } 

    render() { 
    return (
     <div className="ui one cards"> 
      <div className="card"> 
      <div className="content"> 
       <div className="header">Program description</div> 
       <div className="description package" onMouseEnter={ this.showIcon } 
       onMouseLeave={ this.hideIcon }> 
       <i ref="edit" id="edit-icon" className="edit icon"/> 
       <p id="desc"> 
        Lorem Ipsum</p> 
       </div> 
      </div> 
      </div> 
     </div> 
    ); 
    } 
} 

但很顯然,即時得到這個錯誤,每當我懸停:

Uncaught TypeError: Cannot read property 'edit' of undefined 

即使我確實有REF =「編輯」的元素。儘管componentDidMount()函數的代碼確實可以工作,所以我假定showIcon()和hideIcon()中的引用都是在「edit」元素被渲染之前的開始時生成的。我認爲,這只是js的「愚蠢」,並沒有按照原樣閱讀我的功能。

反正,我該如何解決這個問題?關於國家的事情?

+3

[無法訪問做出反應的實例(本)事件處理中(HTTP的可能重複:// stackoverflow.com/questions/29577977/unable-to-access-react-instance-this-inside-event-handler) –

+0

@FelixKling那個答案很模糊,我很難得到它的工作 – pizzae

回答

3

它,因爲你那麼它的上下文是事件,而不是反應,可以綁定功能,它在兩個方面

1.constructor(首選方式)

this.showIcon = this.showIcon.bind(this) 

再未綁定功能在JSX使用

this.showIcon 
  • 在JSX

    //的

    //使用

    this.showIcon.bind(this)

    代替

    this.showIcon

  • +1

    你也可以使用箭頭函數 - {()=> this.showIcon()} –

    +0

    對不起,這個也很模糊。對於React,我很新,所以我想知道這些代碼到底發生了什麼。謝謝。 – pizzae

    +0

    只是添加在構造函數中,請檢查我給出的第一個示例 – abhirathore2006