四、React事件处理
一、事件绑定
React元素的事件处理和DOM元素的很相似,但是有一点语法上的不同,
1 // 函数组件事件绑定 2 import React from "react"; 3 4 const clickHandler = () => { 5 console.log("海纳百川有容乃大,壁立千仞无欲则刚。"); 6 }; 7 8 const App = () => { 9 return <button onClick={clickHandler}>老林说</button>; 10 }; 11 12 export default App;
1 // 类组件事件绑定 2 import React, { Component } from 'react'; 3 class App extends Component{ 4 render() { 5 return ( 6 <div> 7 <!-- 使用JSX 语法时,需要传入一个函数作为事件处理函数--> 8 <button onClick={this.clickHandler}>老林说</button> 9 </div> 10 ) 11 } 12 clickHandler() { 13 console.log('海纳百川有容乃大,壁立千仞无欲则刚。') 14 } 15 }
二、事件对象
1、React中可以通过,事件处理函数的参数,获取到事件对象
2、它的事件对象叫做:合成事件,即兼容所有浏览器,无需担心跨浏览器兼容问题
3、React中的事件对象并不是浏览器提供的,而是它自己内部所构建的
4、
5、
1 import React, { Component } from "react"; 2 3 class App extends Component { 4 render() { 5 return ( 6 <div> 7 <button onClick={this.clickHandler}>老林说</button> 8 </div> 9 ); 10 } 11 clickHandler(e) { 12 console.log("海纳百川有容乃大,壁立千仞无欲则刚。"); 13 console.log(e); 14 console.log(e.target); // dom对象 15 console.log(e.nativeEvent); // 浏览器原生事件对象 16 } 17 } 18 19 export default App;
三、事件方法传参
React中对于事件方法传参的方式有着非常灵活的用法。
1 import React, { Component } from "react"; 2 3 class App extends Component { 4 render() { 5 return ( 6 <div> 7 <button onClick={this.clickHandler}> 8 老林说 9 </button> 10 </div> 11 ); 12 } 13 clickHandler() { 14 console.log(this); 15 } 16 } 17 18 export default App;
解决this指向问题的方法
1、通过类组件的构造函数进行绑定
1 import React, { Component } from "react"; 2 3 class App extends Component { 4 constructor(props) { 5 super(props) 6 this.clickHandler = this.clickHandler.bind(this) 7 } 8 render() { 9 return ( 10 <div> 11 <button onClick={this.clickHandler}> 12 老林说 13 </button> 14 </div> 15 ); 16 } 17 clickHandler() { 18 console.log(this); 19 } 20 } 21 22 export default App;
2、使用bind绑定
1 import React, { Component } from "react"; 2 3 class App extends Component { 4 render() { 5 return ( 6 <div> 7 <button onClick={this.clickHandler.bind(this)}> 8 老林说 9 </button> 10 </div> 11 ); 12 } 13 clickHandler() { 14 console.log(this); 15 } 16 } 17 18 export default App;
3、使用箭头函数:方式一
1 import React, { Component } from "react"; 2 3 class App extends Component { 4 render() { 5 return ( 6 <div> 7 <button onClick={() => this.clickHandler()}>老林说</button> 8 </div> 9 ); 10 } 11 clickHandler() { 12 console.log(this); 13 } 14 }
4、使用箭头函数:方式二
1 import React, { Component } from "react"; 2 3 class App extends Component { 4 render() { 5 return ( 6 <div> 7 <button onClick={this.clickHandler}>老林说</button> 8 </div> 9 ); 10 } 11 clickHandler = () => { 12 console.log(this); 13 } 14 } 15 16 export default App;

浙公网安备 33010602011771号