React.JS这个.状态未定义

React.JS this.state is undefined

本文关键字:未定义 状态 这个 JS React      更新时间:2023-09-26

我目前在React.JS中有这个组件,它在数组中显示传递给它的所有图像,onMouseOver它在下面显示一个按钮。我计划使用setState来检查变量悬停是否为真或假,并相应地切换该图像的按钮,但我一直得到以下错误:

Uncaught TypeError: Cannot read property 'state' of undefined

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>
);
}
});

您得到错误,因为您将对this的引用存储在您用来引用事件处理程序的that变量中,但您没有在三元表达式中使用它来确定button元素的className

代码:

<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时,你不会得到错误。

顺便说一句,你可以简单地将一个上下文参数传递给map()方法,而不是将对this的引用存储在that变量中。

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

在ES5格式中不能设置。国家直接

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 (){ ... }
}