[英]Handle good onClick on ReactJS
我有一個帶有onClick處理程序的完整視圖,並且該視圖內有一個帶有自己的onClick處理程序的按鈕。 我希望在單擊按鈕上除按鈕之外的任何位置時觸發綁定到視圖的onclick。 我希望綁定到按鈕的onclick僅在單擊按鈕時才觸發。
onClick(event){
event.stopPropagation();
this.props.onClick(this.props.item)
}
onDeleteClick(){
}
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={() => {this.onDeleteClick()}} 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>
)
}
只需將事件傳遞給onDelete
處理程序並停止傳播即可:
onClick(event){
event.stopPropagation();
this.props.onClick(this.props.item)
}
onDeleteClick(event){
event.stopPropagation();
//do something
}
render() {
return (
<Paper onClick={ e => this.onClick(e) }>
///
<Button onClick={ e => this.onDeleteClick(e) } >Your button</Button>
///
</Paper>
)
}
在這種情況下,您需要安裝另一個npm
模塊,稱為react-onclickoutside
。根據需要InnerButtonComponent
兩個單獨的組件,例如FullViewComponent
和InnerButtonComponent
。 使用InnerButtonComponent
渲染視圖。 然后在你的
InnerButtonComponent.js
import React from 'react';
import onClickOutside from 'react-onclickoutside';
class InnerButtonComponent extends React.Component {
constructor(props) {
super(props);
}
handleClickOutside (e) {
// outside click staff here
console.log(e);
}
render () {
return (
<div>....</div>
);
}
}
export default onClickOutside(InnerButtonComponent);
而已。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.