2016-11-15 103 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