[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 ...
随机推荐
- LuoguP3356 火星探险问题(费用流)
题目描述 火星探险队的登陆舱将在火星表面着陆,登陆舱内有多部障碍物探测车.登陆舱着陆后,探测车将离开登陆舱向先期到达的传送器方向移动.探测车在移动中还必须采集岩石标本.每一块岩石标本由最先遇到它的探测 ...
- lastlog---显示系统中所有用户最近一次登录信息。
lastlog命令用于显示系统中所有用户最近一次登录信息. lastlog文件在每次有用户登录时被查询.可以使用lastlog命令检查某特定用户上次登录的时间,并格式化输出上次登录日志/var/log ...
- IDLE的自动补全功能
IDLE的自动补全功能位于:Edit→Show Completions,但每次需要补全的时候都需要点击一次,虽然IDLE提供了一个快捷键(Ctrl + Space),但实测无效.具体操作如下图
- inode与ln命令
inode可以看: http://www.cnblogs.com/itech/archive/2012/05/15/2502284.html 每个inode节点的大小,一般是128字节或256字节.i ...
- hdoj-1870-愚人节的礼物(栈)
愚人节的礼物 Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Sub ...
- 制作 wordpress 博客静态化到本地
wget 克隆 wordpress 博客镜像 wget -e robots=off -w 1 -xq -np -nH -pk -m -t 1 -P "./wordpress.org" ...
- php中this,self,parent三个关键字的区别辨析
php中this,self,parent三个关键字的区别辨析 一.总结 一句话总结:this是指向对象实例的一个指针,self是对类本身的一个引用,parent是对父类的引用. 1.self关键字使用 ...
- excel表如何实现多if选择结构多分支判断
excel表如何实现多if选择结构多分支判断 一.总结 一句话总结:把多if分支转换成单if分支相加. 也可以if分支,也可以lookup函数. 1.CHOICE: +2 if band A; +1 ...
- Linux启动(续)
runlevel (启动级别): 查看命令 :who -r 或 runlevel 0:halt 关机 1:单用户模式,直接以管理员身份登录,不需要密码 ...
- 手把手教你用NDK9编译ffmpeg2.4.2
编译环境: 32位 ubuntu12.10 android-ndk-r9c-linux-x86.tar.bz2 ffmpeg-2.4.2.tar.bz2 网上的教程都是以低版本号ffmpeg编译居多. ...