循环内的 React 事件绑定未定义
React event binding inside loop is undefined
我在 return 之前的 react render 方法循环中添加了一个点击事件,代码如下
renderedCheckboxes = content.map( function(f, i) {
if ( f['acf_fc_layout'] === 'checkbox' ) {
let id="customCheck" + i;
return (
<li className="list-group-item" key={i}>
<div className="custom-control custom-checkbox">
<input type="checkbox" name={f.checkbox} onClick={this.handleClick.bind(this) } className="custom-control-input" id={id} />
<label className="custom-control-label" htmlFor={id}>{f.label}</label>
</div>
</li>
)
}
});
但是当我点击复选框时我得到 TypeError: Cannot read property 'handleClick' of undefined
在这种情况下我做错了什么?
更改为箭头函数,使 this
在范围内:
renderedCheckboxes = content.map((f, i) => {
if ( f['acf_fc_layout'] === 'checkbox' ) {
let id="customCheck" + i;
return (
<li className="list-group-item" key={i}>
<div className="custom-control custom-checkbox">
<input type="checkbox" name={f.checkbox} onClick={this.handleClick.bind(this) } className="custom-control-input" id={id} />
<label className="custom-control-label" htmlFor={id}>{f.label}</label>
</div>
</li>
)
}
});
您的 this.handleClick
不存在于地图函数的范围内。通过在 map 函数之前写入 const that = this;
来缓存它并使用 that.handleClick
我在 return 之前的 react render 方法循环中添加了一个点击事件,代码如下
renderedCheckboxes = content.map( function(f, i) {
if ( f['acf_fc_layout'] === 'checkbox' ) {
let id="customCheck" + i;
return (
<li className="list-group-item" key={i}>
<div className="custom-control custom-checkbox">
<input type="checkbox" name={f.checkbox} onClick={this.handleClick.bind(this) } className="custom-control-input" id={id} />
<label className="custom-control-label" htmlFor={id}>{f.label}</label>
</div>
</li>
)
}
});
但是当我点击复选框时我得到 TypeError: Cannot read property 'handleClick' of undefined
在这种情况下我做错了什么?
更改为箭头函数,使 this
在范围内:
renderedCheckboxes = content.map((f, i) => {
if ( f['acf_fc_layout'] === 'checkbox' ) {
let id="customCheck" + i;
return (
<li className="list-group-item" key={i}>
<div className="custom-control custom-checkbox">
<input type="checkbox" name={f.checkbox} onClick={this.handleClick.bind(this) } className="custom-control-input" id={id} />
<label className="custom-control-label" htmlFor={id}>{f.label}</label>
</div>
</li>
)
}
});
您的 this.handleClick
不存在于地图函数的范围内。通过在 map 函数之前写入 const that = this;
来缓存它并使用 that.handleClick