React.JS这个.状态未定义
React.JS this.state is undefined
我目前在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 (){ ... }
}
相关文章:
- 为什么“;未定义的“;在JavaScript中结束循环
- 要求未定义JS回调参数
- 如何检查管道中未定义的项目
- TypeError:无法读取属性'推'未定义的JavaScript
- $window.ga在AngularJS事件中未定义
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 未捕获的类型错误:无法读取属性'状态'的未定义
- Chrome - 即使先检查也无法读取未定义的属性“状态”
- ng-model 在声明$parent后保持未定义状态
- 角度显示类型错误:无法读取未定义的属性“状态”
- ReactJS中初始状态的未定义值
- 不能访问React对象状态上的object属性,即使它存在.返回未定义
- 简单JSON保持未定义状态
- Safari中的历史API - pushState / replaceState -状态未定义
- React.JS这个.状态未定义
- AJAX ReadyState 4状态200,但responseText未定义
- 未捕获的ReferenceError:未定义状态
- Redux 状态在更新后返回未定义
- 当试图作为道具传递时,React状态变量意外未定义
- AJAX Get状态正常,但json回调返回未定义的数据