[React] Close the menu component when click outside the menu
Most of the time, your components respond to events that occur within the component tree by defining their own handler or by accepting a handler defined by a parent component via props. Sometimes, this isn't enough. In this lesson, we'll rely on lifecycle hooks and good old fashioned DOM events to update state in a React component in response to an event that occurs outside of the component tree.
class Menu extends React.Component {
constructor(props) {
super(props)
this.state = {
isVisible: false
}
this.handleClickOutside = this.handleClickOutside.bind(this)
this.toggleOptions = this.toggleOptions.bind(this)
this.handleClick = this.handleClick.bind(this)
}
componentDidMount() {
document.addEventListener('click', this.handleClickOutside)
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClickOutside)
}
handleClickOutside(evt) {
if (!this.node.contains(evt.target)) {
this.setState({ isVisible: false })
}
}
toggleOptions(evt) {
evt.preventDefault()
this.setState(state => ({ isVisible: !state.isVisible }))
}
handleClick(choice, evt) {
evt.preventDefault()
this.props.handleMenuChoice(choice)
this.setState({ isVisible: false })
}
render() {
return (
<div className="menu" ref={el => (this.node = el)}>
<a href="#" onClick={this.toggleOptions}>
Options
</a>
{this.state.isVisible
? <div className="menuContents">
<a href="#" onClick={this.handleClick.bind(null, 'one')}>
One
</a>
<a href="#" onClick={this.handleClick.bind(null, 'two')}>
Two
</a>
<a href="#" onClick={this.handleClick.bind(null, 'three')}>
Three
</a>
<a href="#" onClick={this.handleClick.bind(null, '')}>
Clear Selection
</a>
</div>
: null}
</div>
)
}
}
The most important thing is how to detect whether user click outside the menu or not.
To do that, we use 'ref':
<div className="menu" ref={el => (this.node = el)}>
We assign the elememt to vairable 'this.node'.
console log the node:
<div class="menu">
<a href="#">options</a>
</div>
When we click inside the menu, the 'evt.target' is the 'a' tag.
If we click outside the menu, then then 'evt.target' is the whole html tag.
Therefore, we can check:
if (!this.node.contains(evt.target)) {
[React] Close the menu component when click outside the menu的更多相关文章
- React.createClass和extends Component的区别
React.createClass和extends Component的区别主要在于: 语法区别 propType 和 getDefaultProps 状态的区别 this区别 Mixins 语法区别 ...
- React Native 中的component 的生命周期
React Native中的component跟Android中的activity,fragment等一样,存在生命周期,下面先给出component的生命周期图 getDefaultProps ob ...
- React 的 PureComponent Vs Component
一.它们几乎完全相同,但是PureComponent通过prop和state的浅比较来实现shouldComponentUpdate,某些情况下可以用PureComponent提升性能 1.所谓浅比较 ...
- 【转】Pro Android学习笔记(三十):Menu(1):了解Menu
目录(?)[-] 创建Menu MenuItem的属性itemId MenuItem的属性groupId MenuItem的属性orderId MenuItem的属性可选属性 Menu触发 onOpt ...
- [React Native] Create a component using ScrollView
To show a list of unchanging data in React Native you can use the scroll view component. In this les ...
- [React] Write a stateful Component with the React useState Hook and TypeScript
Here we refactor a React TypeScript class component to a function component with a useState hook and ...
- [React] Refactor a Class Component with React hooks to a Function
We have a render prop based class component that allows us to make a GraphQL request with a given qu ...
- 关于React的Container&Presentational Component模型结构分析
react.js javascript 3 之前翻译了两篇关于Container&Presentational Component模型的文章,一篇是基础的Container和Component ...
- [React Router v4] Use the React Router v4 Link Component for Navigation Between Routes
If you’ve created several Routes within your application, you will also want to be able to navigate ...
随机推荐
- 基于SVM的数据分类预測——意大利葡萄酒种类识别
update:把程序源代码和数据集也附上http://download.csdn.net/detail/zjccoder/8832699 2015.6.24 --------------------- ...
- Extjs 4.2 设置buttontext为中文
能够在Ext.QuickTips.init();后增加例如以下代码: Ext.MessageBox.buttonText = { ok : "确定", cancel : " ...
- Timus 1935. Tears of Drowned 具体解释
Old Captain Jack Sparrow's friend Tia Dalma, the fortuneteller and prophetess, often makes potions. ...
- 内网使用 IPV6 之 Chrome 浏览器 扩展程序 篇
手机端的 Google Chrome 浏览器在打开 "流量节省程序"后,它会通过 Google 的服务器中转流量,这台服务器支持 IPV4 和 IPV6.想在PC端使用类似的&qu ...
- 深入理解Android(2)——理解Android中的JNI(中)
阳光小强参加了CSDN博客之星评选,如果你觉得阳光小强的博客对你有所帮助,为小强投上一票吧:http://vote.blog.csdn.net/blogstar2014/details?usernam ...
- Linux下截图技巧
在需要Linux显示图片的场合,最普通的方法,会考虑用数码相,或是用Vmware,或VPc来抓拍,这样以来会比较麻烦,Linux也自带了些工具例如Gimp,ksnapshot这里我介绍一 ...
- JCameraView 仿微信拍照Android控件(点击拍照,长按录小视频)
JCameraView 控件介绍 这是一个模仿微信拍照的Android开源控件,主要的功能有如下: 点击拍照. 前后摄像头的切换. 长按录视频(视频长度为10秒内). 长按录视频的时候,手指上滑可以放 ...
- J2msi 自己制作的把exe打成安装包简易GUI程序
因为wix是用命令行执行的,操作比较麻烦,所以自己写了个wix生成安装包的图形操作程序, 原理很简单,主要用java 来执行 wix 的heat .candle 和 light 命令 ,最后生成安装文 ...
- 03004_SQL语句
1.SQL语法 (1)数据库是不认识JAVA语言的,但是我们同样要与数据库交互,这时需要使用到数据库认识的语言SQL语句,它是数据库的代码: (2)结构化查询语言(Structured Query L ...
- 深入具体解释SQL中的Null
NULL 在计算机和编程世界中表示的是未知,不确定.尽管中文翻译为 "空", 但此空(null)非彼空(empty). Null表示的是一种未知状态.未来状态,比方小明兜里有多少钱 ...