ReactJS中如何处理视图与内部按钮的onClick事件冲突
解决视图与内部按钮的点击事件冲突问题
看起来你现在遇到的问题是点击Delete按钮时,会同时触发按钮的删除事件和外层Paper的点击事件对吧?这是因为事件冒泡的机制——子元素的事件会向上传递到父元素,所以按钮的点击事件触发后,会继续冒泡到外层的Paper组件,触发它的onClick。
要实现「点击按钮只触发按钮事件,点击视图其他区域触发视图事件」的需求,只需要在按钮的点击事件处理函数里阻止事件冒泡就可以了。
修改方案
你需要修改按钮的点击事件处理逻辑,在其中调用event.stopPropagation():
onDeleteClick(event){ // 阻止事件冒泡到父元素 event.stopPropagation(); // 这里写你的删除逻辑 } // 然后在render里的Button组件中传递event参数 <Button onClick={(event) => {this.onDeleteClick(event)}} style={{backgroundColor : "black", color : "white", marginLeft : 70, overflow : "hidden"}}>Delete</Button>
或者也可以直接在Button的onClick回调里直接处理,写法更简洁:
<Button onClick={(event) => { event.stopPropagation(); this.onDeleteClick(); }} style={{backgroundColor : "black", color : "white", marginLeft : 70, overflow : "hidden"}}>Delete</Button>
原理说明
event.stopPropagation()方法会阻止当前事件继续向上冒泡传播,这样点击按钮时,只有按钮自身的点击事件会被执行,外层Paper的onClick事件不会被触发。- 当你点击视图中除按钮外的其他区域时,没有元素阻止事件冒泡,所以事件会正常传递到Paper组件,触发它的onClick事件,完全符合你的需求。
完整修改后的代码片段
onClick(event){ event.stopPropagation(); this.props.onClick(this.props.item) } onDeleteClick(event){ event.stopPropagation(); // 这里添加你的删除操作逻辑 } render(){ const paper = { height: 180, width: 400, backgroundColor : "#ECEFF1", display : "flex", flexDirection : "column", cursor: this.state.cursor } const littlePartStyle = { width : "100%", height : 40, display : "flex", alignItems : "center", marginLeft : 30 } return( <Paper onClick={(event) => {this.onClick(event)}} onMouseLeave={() => {this.onMouseLeft()}} onMouseOver={() => {this.onMouseOver()}} style={paper} > <div style={{width : "100%", height : "30%", alignItems : "center", display : "flex"}}> <div style={{display : "flex", marginLeft : 30, width : "50%", fontSize : 20}}>{this.props.item.name}</div> <div style={{width : "50%"}}> <Button onClick={(event) => {this.onDeleteClick(event)}} style={{backgroundColor : "black", color : "white", marginLeft : 70, overflow : "hidden"}}>Delete</Button> </div> </div> <div style={{width : "100%", height : "70%", display : "flex", flexDirection : "column"}}> <div style={littlePartStyle}> <div>Session organizer : {this.props.item.organizer}</div> </div> <div style={{width : "80%", height : 1, backgroundColor : "black", marginLeft : 30}}> </div> <div style={littlePartStyle}> <div>Session subject : {this.props.item.subject}</div> </div> <div style={{width : "80%", height : 1, backgroundColor : "black", marginLeft : 30}}> </div> <div style={littlePartStyle}> <div>Creation date : {this.props.item.creationDate}</div> </div> </div> </Paper> ) }
内容的提问来源于stack exchange,提问作者Psyycker
相关产品推荐
相关产品推荐

