我收到Cannot read property 'clickHandler' of undefined
var FilterableProductTable = React.createClass({
render: function() {
var rows = [];
this.props.products.forEach(function(product) {
if( product.Control == "" || product.Control == undefined) {
rows.push(<tr colSpan = "2" key = {product.Field}><th>{product.Field}</th><td></td></tr>); //rows.push( < ProductHeader product = { product } key = { product.Field } /> );
}
else {
var ControlTag;
if(product.Control == "textarea") {
ControlTag = <span><textarea rows="4" cols="18" id={ product.id } title={ product.id }></textarea><i className="fa fa-pencil changeSetting" title="Change control"></i></span>
}
else if(product.Control == "select") {
ControlTag = <span><select style={{width: '60%'}} id={ product.id } title={ product.id }><option></option></select><i className="fa fa-pencil changeSetting" title="Change control"></i></span>
}
else {
ControlTag=<span><input type="text" id={ product.id } title={ product.id }/><i className="fa fa-pencil changeSetting" title="Change control"></i></span>
}
rows.push(<tr colSpan = "2" key = {product.Field}><th>{product.Field}</th><td onClick={ this.clickHandler }>{ControlTag}</td></tr>); // rows.push( < ProductRow product = { product } key = { product.Field } />);
}
});
return ( <table className={'tagsTable'}><tbody>{rows}</tbody></table> )
},
clickHandler: function(e){ alert(); }
});
代码中是否缺少某些内容?
答案 0 :(得分:2)
您正在使用forEach循环,因此this
内部循环将不是组件本身。
var FilterableProductTable = React.createClass({
render: function() {
var rows = [];
var self = this; // <== new code
this.props.products.forEach(function(product) {
// bunch of code..
// changed click to onClick={ self.clickHandler }
rows.push(<td onClick={ self.clickHandler }>{ControlTag}</td>);
// bunch of code..
});
},
clickHandler: function(e){ alert(); }
});
或者根据Alexander T.的建议设置forEach循环的范围。事实上我比上面的解决方案更喜欢它
var FilterableProductTable = React.createClass({
render: function() {
var rows = [];
this.props.products.forEach(function(product) {
// your code, without any modification
}, this); // <== notice: this
},
clickHandler: function(e){ alert(); }
});
答案 1 :(得分:1)
因为this
在forEach函数中使用,所以它引用了这个函数,而不是你的React组件。使用这个小JS技巧:
var self = this;
this.props.products.forEach(function(product) {
<td onClick={ self.clickHandler }></td>
}