[英]A small question about a custom react modal component
我用reactjs創建了一個模態組件,它由模態掩碼和模態主體組成。 現在我想單擊模式蒙版,將整個模式組件隱藏起來。
嘗試在模式蒙版dom上添加單擊事件
class Modal extends React.Component {
onClose = () => {
console.log('close')
}
render () {
return (
<div>
<div className="mocal-mask" onClick={this.onClose}>
</div>
<div className="modal-body">
</div>
</div>
)
}
}
.modal-mask {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.8);
}
.modal-body {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: none;
}
onClick
函數應為控制台“關閉”
您正在將一個函數this.onClose
傳遞給onClick
事件,但已將函數命名為onClick
,您需要定義一個名為onClose
的函數
onClose = () => {
console.log('close')
}
您基本上可以通過兩種方式處理此問題
來自父組件
handleClose = () => { this.setState({modal: false}) } // in render { this.state.modal && <Modal onClose={this.handleClose}>}
您可以在模式本身中進行操作
handleClose = () => { this.setState({modal: false}) } // in render return ( this.state.modal ? <div>...<div> : '' )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.