React Event 事件系統
React事件
React 標準化了事件物件,因此在不同的瀏覽器中都會有相同的屬性。
元件createClass後建立的是許多方法組成的物件。元件中使用的方法分為React自有的方法與使用者定義的方法。其中React自有方法是元件生命週期中的方法,如:render
、componentWillUpdate
、componentDidMount
等。使用者自定義的方法可以起符合JS命名規範的方法就可以(最好使用駝峰命名),如:handleClick
、handleChange
、handleMouseover
等。
事件繫結語法:onClick = {this.handleClick}
事件繫結函式
滑鼠類
onClick
onContextMenu
onDoubleClick
onMouseDown
onMouseEnter
onMouseLeave
onMouseMove
onMouseOut
onMouseOver
onMouseUp
拖拽事件:
onDrop
onDrag
onDragEnd
onDragEnter
onDragExit
onDragLeave
onDragOver
onDragStart
觸控
onTouchCancel
onTouchEnd
onTouchMove
onTouchStart
觸控只會在移動裝置上產生
鍵盤
onKeyPress
是onKeyDown
和onKeyUp
的組合
onKeyDown
onKeyPress
onKeyUp
剪下類
onCopy
onCut
onPaste
對應的是我們常常使用的複製、剪下和貼上
表單類
onChange
onInput
onSubmit
onChange
可以用在輸入框、單選框、下拉列表裡,每當內容發生變化時我們都能獲得通知。onInput
onSubmit
是用在整個表單的輸入提交,常用在禁止表單的預設操作。
焦點事件
onFocus
onBlur
UI元素類
onScroll
滾動事件觸發的時候會觸發onScroll事件
滾動
onWheel
滑鼠滾輪觸發的事件,監聽滾動幅度,滾動方位
組成事件
onCompositionEnd
onCompositionStart
onCompositionUpdate
圖片類
onLoad
onError
多媒體類
onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting
例項演示
let HelloDada = React.creatClass({
getInitialState:function(){
return{
name:''
};
},
handleChange:function(e){
this.setState({
name:e.target.value
});
},
render:function(){
return (
<div>
<input onChange={this.handleChange} />
</div>
);
}
});
ReactDom.render(<HelloDada/>,document.body);
事件池
虛擬事件物件已經被合併。這意味著虛擬事件物件將被重新使用,而該事件回撥被呼叫之後所有的屬性將無效。這是出於效能的考慮。因此,您不能以非同步的方式訪問事件。
function onClick(event) {
console.log(event); // =>無效的物件
console.log(event.type); // => "click"
var eventType = event.type; // => "click"
setTimeout(function() {
console.log(event.type); // => null
console.log(eventType); // => "click"
}, 0);
this.setState({clickEvent: event}); // 不起作用.this.state.clickEvent 將只包含空值.
this.setState({eventType: event.type}); // 您依然可以匯出事件屬性
}
如果您想以一個非同步的方式來訪問事件屬性,您應該對事件呼叫
event.persist()
。這將從事件池中取出合成的事件,並允許該事件的引用,使使用者的程式碼被保留。
事件物件
事件處理器將會傳入SyntheticEvent
的例項,一個對瀏覽器本地事件的跨瀏覽器封裝。它有和瀏覽器本地事件相同的屬性和方法,包括stopPropagation()
和preventDefault()
,但是沒有瀏覽器相容問題。如果因為一些因素,需要底層的瀏覽器事件物件,只要使用nativeEvent
屬性就可以獲取到它了。
對於 v0.14,在事件處理函式中返回 false 將不會阻止事件冒泡。取而代之的是在合適的應用場景下,手動呼叫
e.stopPropagation()
或者e.preventDefault()
。
handleChange:function(e){ console.log(e.target.value); }
其中e
是事件物件target
是事件物件的屬性
(以下內容括號內為型別)
通用屬性
-
bubbles (boolean) 表示事件是否冒泡
-
cancelable(boolean) 表示事件是否可以取消
-
currentTarget(DOMEventTarget) 與Target類似,由於事件可以冒泡,所以兩者表示的內容是不同的
-
defaultPrevented(boolean) 表示事件是否禁止了預設行為
-
eventPhase(number) 表示事件所處的階段
-
isTrusted(boolean) 表示事件是否可信。所謂的可信事件表示的是使用者操作的事件,不可信事件就是通過JS程式碼來觸發的事件。
-
nativeEvent(DOMEvent)
-
preventDefault() (void) 對應的defaultPrevented,表示的是禁止預設行為
-
stopPropagaTion() (void) 對應的是bubbles,表示的是sh
-
target(DOMEventTarget)
-
timeStamp(number) 時間戳,也就是事件觸發的事件
-
type(string) 事件的型別
不同事件物件的特有屬性
剪下事件
-
clipboardData(DOMDataTransfer)表示拿到的資料
鍵盤事件
-
altKey(boolean) 表示是否按下alt鍵
-
charCode(Number) 表示的是按鍵的字元編碼,可以通過編碼來判斷按下的是什麼鍵
-
ctrlKey(boolean) 表示是否按下ctrl鍵
-
getModifierState(key) (function) 表示是否按下輔助按鍵(輔助按鍵就是雷士ctrl、shift等輔助按鍵)可以傳入按鍵編碼來判斷是否按下
-
key(string) 字串,按下的鍵
-
keyCode(Number) 表示那些不是字元編碼的按鍵
-
locale(String) 表示本地化得一些字串
-
location(number) 表示位置
-
metaKey(boolean) 表示的是win系統下的win鍵,mac系統下對應的command鍵
-
repeat(boolean) 表示按鍵是否重複
-
shiftKey(boolean) 表示是否按下shift
-
which(Number) 表示經過通用化得charCode和keyCode
焦點事件
-
relatedTarget(DOMEventTarget) 相關焦點物件
滑鼠事件
-
altKey(boolean)
-
button(Number)
-
buttons(Number)
-
clientX(Number) 原點為瀏覽器左上角
-
clinetY(Number) 原點為瀏覽器左上角
-
ctrlKey(boolean)
-
getModifierState(key) (function)
-
metaKey(boolean)
-
pageX(Number) 原點為HTML頁面的左上角
-
pageY(Number) 原點為HTML頁面的左上角
-
relatedTarget(DOMEventTarget)
-
screenX(Number) 原點為顯示器的左上角
-
screenY(Number) 原點為顯示器的左上角
-
shiftKey(boolean)
觸控事件
為了使觸控事件生效,在渲染所有元件之前呼叫
React.initializeTouchEvents(true)
。
-
altKey(boolean)
-
ctrlKey(boolean)
-
getModifierState(key)
-
metaKey(boolean)
-
shiftKey(boolean)
-
changedTouches(DOMTouchList) 判斷手勢操作
-
targetTouches(DOMTouchList) 判斷手勢操作
-
touches(DOMTouchList) 判斷手勢操作
UI元素事件
-
detail(Number) 滾動的距離
-
view(DOMAbstractView) 介面,視窗
滑鼠滾動
-
deltaMode(Number) 可以理解為移動的單位
-
deltaX(Number) X軸移動的相對距離固定值
-
deltaY(Number) Y軸移動的相對距離固定值
-
deltaZ(Number) Z軸移動的相對距離固定值
例項
-
滾動事件物件
var HelloDada = React.creatClass({
getInitialState:function(){
return {
backgroundColor:'#FFFFFF'
}
},
handleWheel:function(e){
var newColor = (parseInt(this.state.backgroundColor.substr(1),16)+e.deltaY*997).tiString(16);
this.setState({
backgroundColor:newColor
})
},
render:function(){
return <div onWheel={this.handleWheel} style={this.state}>
<p>Dada Shuaige</p>
</div>
}
});
ReactDOM.render(<HelloDada />,document.body)
2.鍵盤事件物件
let Dada =React.creatClass{
getInitialState:function(){
return{
password:''
}
},
handleKeyPress:function(e){
this.setState({
paddword:this.state.password+e.which
});
},
handleChange:function(e){
e.target.value='';
},
render:function(){
return <div>
<input onKeyPress={this.handleKeyPress} onChange={this.handleChange} />
<p style={{
'display':this.state.password.indexOf('1') >=0?'block':'none'
}}>Dada handsomeboy</p>
</div>
}
};
ReactDOM.render(<Dada />,document.body)
事件與狀態關聯
狀態不僅僅實現了元件內部結果的清晰對應,還實現了元件與使用者之間的互動,使使用者與元件的行為緊緊結合起來
handleChange:function(e){ this.setState({Dada:e.target.value}); }
this.setState設定狀態
例項
let Dada =React.creatClass({
getInitialState:function(){
return{
x:0,
y:0
}
},
handleMouseMove:function(e){
this.setState({
x:e.clientX,
y:e.clientY
});
},
render:function(){
return <div onMouseMove={this.handleMouseMove} style={{
width:'200px',
height:'200px',
backgroundColor:'#999'
}}>
{this.state.x+'.'+this.state.y}
</div>
}
});
ReactDOM.render(<Dada />,document.body)
React原文說明
SyntheticEvent
This reference guide documents the SyntheticEvent
wrapper that forms part of React’s Event System. See the Handling Events guide to learn more.
Overview
Your event handlers will be passed instances of SyntheticEvent
, a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation()
and preventDefault()
, except the events work identically across all browsers.
If you find that you need the underlying browser event for some reason, simply use the nativeEvent
attribute to get it. Every SyntheticEvent
object has the following attributes:
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
Note:
As of v0.14, returning
false
from an event handler will no longer stop event propagation. Instead,e.stopPropagation()
ore.preventDefault()
should be triggered manually, as appropriate.
Event Pooling
The SyntheticEvent
is pooled. This means that the SyntheticEvent
object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.
function onClick(event) { console.log(event); // => nullified object. console.log(event.type); // => "click" const eventType = event.type; // => "click" setTimeout(function() { console.log(event.type); // => null console.log(eventType); // => "click" }, 0); // Won't work. this.state.clickEvent will only contain null values. this.setState({clickEvent: event}); // You can still export event properties. this.setState({eventType: event.type}); }
Note:
If you want to access the event properties in an asynchronous way, you should call
event.persist()
on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
Supported Events
React normalizes events so that they have consistent properties across different browsers.
The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture
to the event name; for example, instead of using onClick
, you would use onClickCapture
to handle the click event in the capture phase.
Reference
Clipboard Events
Event names:
onCopy onCut onPaste
Properties:
DOMDataTransfer clipboardData
Composition Events
Event names:
onCompositionEnd onCompositionStart onCompositionUpdate
Properties:
string data
Keyboard Events
Event names:
onKeyDown onKeyPress onKeyUp
Properties:
boolean altKey number charCode boolean ctrlKey boolean getModifierState(key) string key number keyCode string locale number location boolean metaKey boolean repeat boolean shiftKey number which
The key
property can take any of the values documented in the DOM Level 3 Events spec.
Focus Events
Event names:
onFocus onBlur
These focus events work on all elements in the React DOM, not just form elements.
Properties:
DOMEventTarget relatedTarget
Form Events
Event names:
onChange onInput onInvalid onSubmit
For more information about the onChange event, see Forms.
Mouse Events
Event names:
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp
The onMouseEnter
and onMouseLeave
events propagate from the element being left to the one being entered instead of ordinary bubbling and do not have a capture phase.
Properties:
boolean altKey number button number buttons number clientX number clientY boolean ctrlKey boolean getModifierState(key) boolean metaKey number pageX number pageY DOMEventTarget relatedTarget number screenX number screenY boolean shiftKey
Pointer Events
Event names:
onPointerDown onPointerMove onPointerUp onPointerCancel onGotPointerCapture onLostPointerCapture onPointerEnter onPointerLeave onPointerOver onPointerOut
The onPointerEnter
and onPointerLeave
events propagate from the element being left to the one being entered instead of ordinary bubbling and do not have a capture phase.
Properties:
As defined in the W3 spec, pointer events extend Mouse Events with the following properties:
number pointerId number width number height number pressure number tangentialPressure number tiltX number tiltY number twist string pointerType boolean isPrimary
A note on cross-browser support:
Pointer events are not yet supported in every browser (at the time of writing this article, supported browsers include: Chrome, Firefox, Edge, and Internet Explorer). React deliberately does not polyfill support for other browsers because a standard-conform polyfill would significantly increase the bundle size of react-dom
.
If your application requires pointer events, we recommend adding a third party pointer event polyfill.
Selection Events
Event names:
onSelect
Touch Events
Event names:
onTouchCancel onTouchEnd onTouchMove onTouchStart
Properties:
boolean altKey DOMTouchList changedTouches boolean ctrlKey boolean getModifierState(key) boolean metaKey boolean shiftKey DOMTouchList targetTouches DOMTouchList touches
UI Events
Event names:
onScroll
Properties:
number detail DOMAbstractView view
Wheel Events
Event names:
onWheel
Properties:
number deltaMode number deltaX number deltaY number deltaZ
Media Events
Event names:
onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting
Image Events
Event names:
onLoad onError
Animation Events
Event names:
onAnimationStart onAnimationEnd onAnimationIteration
Properties:
string animationName string pseudoElement float elapsedTime
Transition Events
Event names:
onTransitionEnd
Properties:
string propertyName string pseudoElement float elapsedTime
Other Events
Event names:
onToggle