[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 ...
随机推荐
- js实现动态添加事件
js实现动态添加事件 一.实例描述 前一个案例讲了如何在网页中动态添加元素,有时候我们需要添加事件.本例学习如何动态的为元素添加事件. 二.截图 三.代码 <!DOCTYPE html> ...
- js实现删除确认提示框
js实现删除确认提示框 一.实例描述 防止用户小心单击了“删除”按钮,在用户单击“删除”按钮后,给出一个提示,让用户确认此次操作是否正确. 二.效果 三.代码 <!DOCTYPE html> ...
- 浏览器加载渲染HTML、DOM、CSS、 JAVASCRIPT、IMAGE、FLASH、IFRAME、SRC属性等资源的顺序总结
页面响应加载的顺序: 1.域名解析->加载html->加载js和css->加载图片等其他信息 DOM详细的步骤如下: 解析HTML结构. 加载外部脚本和样式表文件. 解析并执行脚 ...
- javafx KeyCombination
import javafx.application.Application; import javafx.application.Platform; import javafx.event.Actio ...
- Regularized logistic regression
要解决的问题是,给出了具有2个特征的一堆训练数据集,从该数据的分布可以看出它们并不是非常线性可分的,因此很有必要用更高阶的特征来模拟.例如本程序中个就用到了特征值的6次方来求解. Data To be ...
- idea配置spark运行模式
1. 配置运行参数: Menu -> Run -> Edit Configurations -> 选择 + -> Application -Dspark.master=lo ...
- 解决create-react-app 后 npm start 中出现 的webpack版本问题和webpack-dev-server的版本问题
利用VSCode搭建react的脚手架运行环境的时候.create-react-app之后npm start出现如下图的问题: There might be a problem with the pr ...
- UVa 11743 - Credit Check
题目:推断卡号是否合法,给你4组4位的数字.偶数位的2倍的位和加上奇数位的和,推断尾数是否为0. 分析:简单题,模拟. 直接依照提议推断就可以. 说明:460题,加油! #include <io ...
- OpenGL核心技术之混合技术
笔者介绍:姜雪伟,IT公司技术合伙人,IT高级讲师,CSDN社区专家,特邀编辑,畅销书作者.国家专利发明人;已出版书籍:<手把手教你架构3D游戏引擎>电子工业出版社和<Unity3D ...
- 深度学习 Deep LearningUFLDL 最新Tutorial 学习笔记 2:Logistic Regression
1 Logistic Regression 简述 Linear Regression 研究连续量的变化情况,而Logistic Regression则研究离散量的情况.简单地说就是对于推断一个训练样本 ...