Today I added a small function to the component. You need to click on the blank part of the interface to close the current component. After searching for a while, I found that the main method is jquery. There are almost no js native methods and it crashes. . Finally got it out, just make a note for yourself, ps: I use react
The method to be used:
1.contains: It is to determine whether an element is selected. The child element (or itself) of the specified element;
2.window.event.target: Returns the target node of the event. For example, if you click on a
, it will return this h1; (the evil ie does not support it)3.addEventListener: event listening, example, document.body.addEventListener('click',function(){ });
4.ref , this is a method provided by react to select real dom elements, and has the same effect as the js native document.document.getelementby... series
<strong>示例:<br/><p</strong><br/><strong> ref={(r) => {</strong><br/><strong> this.pElem = r;</strong><br/><strong> }}</strong><br/><strong>></strong><br/><strong></p></strong>
The above is the usage of es6, es5 (not recommended) see here
After talking nonsense, the code on the picture above:
Rendering:
Code:
import React, { Component } from 'react'; import './index.less'; class CloseTheDomByClickBlankArea extends Component { state = { openCurrentArea: true, }; componentDidMount() { // 点击blank_area区域,关闭current_area面板 this.blankAreaElem.addEventListener('click', this.handleClickCloseCurrentArea.bind(this)); } handleClickCloseCurrentArea() { // 当界面上渲染出内部面板时,可执行如下操作(若无此判断条件,点击打开面板按钮区域, 就会先触发如下操作,再触发handleClickOpenCurrentArea函数) if (document.body.contains(this.currentAreaElem)) { // 点击面板以外的部分(灰色区域以内,面板区域以外),就关闭面板 if (this.blankAreaElem.contains(window.event.target) && !this.currentAreaElem.contains(window.event.target) ) { this.setState({ openCurrentArea: false, }) } } } // 点击"打开面板"按钮,打开面板 handleClickOpenCurrentArea() { this.setState({ openCurrentArea: true, }) } render() { return ( <p className="blank_area" ref={(r) => { this.blankAreaElem = r; }} > {/* 打开面板按钮 */} <a role="button" tabIndex="0" className="btn_open_current_area" onClick={this.handleClickOpenCurrentArea.bind(this)} > <p className="btn_open_current_area_text">打开面板</p> </a>
{/* 要关闭或开启的面板current_area */}
{ this.state.openCurrentArea && <p className="current_area" ref={(r) => { this.currentAreaElem = r; }} > <p className="current_area_text">点击旁边灰色区域关闭当前面板</p> </p> } </p> ); } } export default CloseTheDomByClickBlankArea;
The above is the detailed content of How to use the contains method to achieve the effect of closing the current panel by clicking on a blank part of the interface. For more information, please follow other related articles on the PHP Chinese website!