Gau*_*tap 8 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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
你得到的错误,因为要存储的参考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>
Run Code Online (Sandbox Code Playgroud)
当您更改this.state.hover到that.state.hover你不会得到错误.
另一方面,您可以简单地将上下文参数传递给方法,而不是将引用存储this在that变量中.map()
results.map(function (result) {
//
}, this);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15422 次 |
| 最近记录: |