React.JS this.state未定义

时间:2015-07-26 11:59:30

标签: javascript reactjs

我目前在React.JS中有这个组件,它显示了在一个数组和onMouseOver中传递给它的所有图像,它在下面显示了一个按钮。我计划使用setState检查变量悬停,如果为true或false,并相应地切换该图像的按钮,但是我不断收到以下错误:

  

未捕获的TypeError:无法读取属性' state'未定义的

var ImageList = React.createClass({
getInitialState: function () {
    return this.state = { hover: false };
},
getComponent: function(index){
      console.log(index);
      if (confirm('Are you sure you want to delete this image?')) {
          // Save it!
      } else {
          // Do nothing!
      }    
},
mouseOver: function () {
    this.setState({hover: true});
    console.log(1);
},

mouseOut: function () {
    this.setState({hover: false});
    console.log(2);
},
render: function() {
var results = this.props.data,
  that = this;
return (
  <ul className="small-block-grid-2 large-block-grid-4">
    {results.map(function(result) {
      return(
              <li key={result.id} onMouseOver={that.mouseOver} onMouseOut={that.mouseOut} ><img className="th" alt="Embedded Image" src={"data:" + result.type + ";"  + "base64," + result.image} /> <button onClick={that.getComponent.bind(that, result.patientproblemimageid)} className={(this.state.hover) ? 'button round button-center btshow' : 'button round button-center bthide'}>Delete Image</button></li>
      )      
    })}
  </ul>
);
}

});

2 个答案:

答案 0 :(得分:5)

您收到错误是因为您在this变量中存储了对that变量的引用,而该变量用于引用您的事件处理程序,但您并非如此在三元表达式中使用它来确定className元素的button

您的代码:

<button
  onClick={ that.getComponent.bind(that, result.patientproblemimageid) } 
  className={ (this.state.hover) ? // this should be that 
    'button round button-center btshow' : 
    'button round button-center bthide'}>Delete Image
</button>

当您将this.state.hover更改为that.state.hover时,您不会收到错误。

在旁注中,您可以简单地将上下文参数传递给this method,而不是将that的引用存储到map()变量中。

results.map(function (result) {
  //
}, this);

答案 1 :(得分:3)

在ES5格式中,您无法直接设置this.state

var ImageList = React.createClass({
getInitialState: function () {
 return { hover: false };
},
render : function(){
return(<p>...</p>);
});

然而,使用新的ES6语法,您基本上可以管理它:

class ImageList extends React.Component{
constructor (props) {
  super(props);
  this.state = {hover : false};
}
render (){ ... }
}