React 页面加载后自动执行onClick事件
<Button className={placeTime.length > 1 ? styles.delBtn : styles.delFirst} onClick={this.onRemove (index)}> <Icon type={'delete'}/>删除 </Button> ) onRemove = (index) => { const { placeTime } = this.state console.log(placeTime, index); placeTime.splice(index, 1) this.setState({ placeTime }) }
---------------------
删除按钮绑定的
onRemove
点击事件,想要带着参数index去执行,但这种操作是不允许的,刚好在事件函数中也有setState操作,这样就会陷入到死循环
中,不停的改变state,render()又不停的被执行。解决方案
// 一 <Button className={placeTime.length > 1 ? styles.delBtn : styles.delFirst} onClick={()=>this.onRemove (index)}> <Icon type={'delete'}/>删除 </Button> // 二 <Button className={placeTime.length > 1 ? styles.delBtn : styles.delFirst} onClick={this.onRemove .bind(this,index)}> <Icon type={'delete'}/>删除 </Button>
苦心人,天不负