contains() 实现点击界面空白部分关闭当前面板的效果
- contains 判断某个元素是不是选定元素的子元素或者本身。
- window.event.target 返回事件的目标节点,比如点击了某个
<div></div>
就会返回div。 - addEventListener 事件监听
window.addEventListener('click',function(){})
- ref 这是react 提供的选择真实DOM的方法。
import React,{ Component,Fragment } from 'react';
import { Button } from 'antd';
class Accessibility extends Component {
constructor(props){
super(props);
this.toggleContainer = React.createRef();
this.onClickOutsideHandler = this.onClickOutsideHandler.bind(this);
this.state = {
isOpen: false,
}
}
componentDidMount() {
window.addEventListener("click",this.onClickOutsideHandler);
}
componentWillUnmount() {
window.addEventListener("click",this.onClickOutsideHandler);
}
ulClick() {
this.setState(currentState=>({
isOpen: !currentState.isOpen
}))
}
onClickOutsideHandler(event) {
console.log('event',this.toggleContainer);
if(this.state.isOpen && !this.toggleContainer.current.contains(event.target)) {
this.setState({isOpen: false})
}
}
render() {
return(
<div>
<div className='border background' ref={ this.toggleContainer}>
<Button type='primary' onClick={ this.ulClick.bind(this)}>Select an option</Button>
{ this.state.isOpen ?
<ul>
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>:null
}
</div>
</div>
)
}
}
export default Accessibility;