Skip to content

Commit

Permalink
issue: synthetic-event
Browse files Browse the repository at this point in the history
  • Loading branch information
afeiship committed Nov 1, 2018
0 parents commit d2d929f
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# react-notes
> React notes.

31 changes: 31 additions & 0 deletions docs/synthetic-event/001-绑定事件.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# 绑定事件
> 在 React 中绑定事件的方式很简单,只需要在元素中添加事件名称的属性已经对应的处理函数,事件名称和其他属性名称一样,服从驼峰式命名。

```js
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);

// 这种方式是效率最高的。

/*
onClick = (inEvent) =>{};
onClick={()=>{//onClick 逻辑}}
都会每次重新生成匿名函数(增加内存开销,既然是匿名函数,就不会自动销毁)
*/

}
render() {
return (
<div>
<button onClick={this.onClick}>Click Me</button>
</div>
);
}
onClick() {
console.log("click me");
}
}
```
54 changes: 54 additions & 0 deletions docs/synthetic-event/002-合成事件.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 合成事件

React 事件处理将接受 `SyntheticEvent` 实例,它封装了浏览器原生事件对象,并对浏览器做了兼容。
他和浏览器原生事件对象有相同的接口,包括 `stopPropagation()``preventDefault()`
如果出于某些原因想使用浏览器原生事件,可以使用 nativeEvent 属性获取。

每个 SyntheticEvent 对象都有下面的属性:

```conf
boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
boolean isDefaultPrevented()
void stopPropagation()
boolean isPropagationStopped()
DOMEventTarget target
number timeStamp
string type
```

## 事件池化
合成事件是池化的,也就是说 SyntheticEvent 对象会被重用,`而且当事件回调函数被执行后所有的属性将被销毁。这也是出于性能的考虑。因此你不能异步访问event`。如:

```js
class HelloWorld extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
// e.persist();
window.setTimeout(function() {
console.log(e);
console.log(e.type);
}, 1000);
}
render() {
return <button onClick={this.handleClick}>click me</button>;
}
}
```

## 用后即焚
当一个事件响应函数执行过后,事件的属性被设置为 null, 如果想用保持事件的值的话,可以调用
```js
event.persist()
```
这样,属性会被保留,并且事件也会被从池中取出。

10 changes: 10 additions & 0 deletions docs/synthetic-event/003-冒泡-捕获事件.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# 支持的事件
React规范化事件以使得在不同浏览器之间保持相同的属性。下面的事件处理程序都是在冒泡阶段触发的。在捕获阶段注册事件处理程序需要在事件名称后添加Capture。比如点击事件,冒泡阶段是onClick,在捕获阶段为onClickCapture.

## 各种事件类型
1) 剪贴板事件(Clipboard Events)
2) 编辑事件(Composition Events)
3) 键盘事件(Keyboard Events)
4) 焦点事件(Focus Events)
。。。。

2 changes: 2 additions & 0 deletions docs/synthetic-event/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# refences:
+ https://www.cnblogs.com/YangqinCao/p/6155560.html

0 comments on commit d2d929f

Please sign in to comment.