我目前在React.JS中具有此组件,该组件以数组形式显示传递给它的所有图像,而onMouseOver则在下面显示一个按钮。我计划使用setState检查变量悬停是否为true或false并相应地切换该图像的按钮,但是我不断收到以下错误:
未捕获的TypeError:无法读取未定义的属性“状态”
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元素。
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.state.hover
that.state.hover
附带说明一下,您可以将上下文参数简单地传递给method,而不是将对它的引用存储this在that变量中。map()
map()
results.map(function (result) { // }, this);