[英]React.JS this.state is undefined
我目前在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>
);
}
});
你得到的错误,因为要存储的参考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
在that
可变就可以简单的通过一个情境参数的map()
方法 。
results.map(function (result) {
//
}, this);
在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 (){ ... }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.