1. 通過onXxx屬性指定事件處理函數(shù)(注意大小寫)
a. React使用的是自定義(合成)事件,而不是使用的原生DOM事件 --- 為了更好的兼容性
b. React中的事件是通過事件委托方式處理的(委托給組件最外層的元素)冒泡原理(高效)
2. 通過event.target得到發(fā)生事件的DOM元素對象
event.target發(fā)生事件的事件源(即事件是在誰身上發(fā)生的)
發(fā)生事件的元素正好是我們要操作的元素(如下右側(cè)輸入框), 所以,請勿過渡使用refs(因為很多時候可以省掉使用,可以通過event.targer得到)
class Demo extends React.Component{ state = {name:"小明"} //創(chuàng)建Ref容器 myRef = React.createRef() myRef2 = React.createRef() //展示左冊輸入框的內(nèi)容 showData = ()=>{ console.log(this.myRef.current.value); } showData2 = (event)=>{ let source = event.target console.log(source); console.log(source.value); } showData3(name){ console.log(name); } render(){ return ( <div> <input ref={this.myRef} type='text' /> <button onClick = {this.showData}>點擊顯示左邊輸入框的內(nèi)容</button> <input type="text" onBlur={this.showData2}/> <button onClick = {this.showData3.bind(this,this.state.name)}>綁定this傳遞參數(shù)</button> </div> ) } } ReactDOM.render(<Demo/>,document.getElementById("test"));