事件处理
绑定事件
采用on+事件名的方式来绑定一个事件,注意,这里和原生的事件是有区别的,原生的事件全是小写onclick
, React里的事件是驼峰onClick
,React的事件并不是原生事件,而是合成事件。
事件handler的写法
- 直接在render里写行内的箭头函数(不推荐)
- 在组件内使用箭头函数定义一个方法(推荐)
- 直接在组件内定义一个非箭头函数的方法,然后在render里直接使用
onClick={this.handleClick.bind(this)}
(不推荐) - 直接在组件内定义一个非箭头函数的方法,然后在constructor里bind(this)(推荐)
Event 对象
和普通浏览器一样,事件handler会被自动传入一个 event
对象,这个对象和普通的浏览器 event
对象所包含的方法和属性都基本一致。不同的是 React中的 event
对象并不是浏览器提供的,而是它自己内部所构建的。它同样具有event.stopPropagation
、event.preventDefault
这种常用的方法
事件的参数传递
- 在
render
里调用方法的地方外面包一层箭头函数 - 在
render
里通过this.handleEvent.bind(this, 参数)
这样的方式来传递 - 通过
event
传递 - 比较推荐的是做一个子组件, 在父组件中定义方法,通过
props
传递到子组件中,然后在子组件件通过this.props.method
来调用
import React,{ Component } from 'react';
import './App.css';
import Home from './component/home'
class App extends Component{
constructor () {
super()
this.change1 = this.change1.bind( this )
}
change = () => {
alert(' hello ')
console.log( this )
}
change1 () {
console.log( this )
}
eventHander ( e ) {
console.log( e )
console.log( e.clientX )
console.log( e.clientY )
}
argumentHandler ( a, b,e ) {
console.log( a, b )
console.log( e )
}
transmitHandler ( a, b ) {
console.log( a, b )
}
render () {
return (
<div className="App">
<h3> React-事件 </h3>
<button onClick = { () => { alert( 2 )} }> 事件第一种写法 - 不推荐 </button>
<button onClick = { this.change }> 事件第二种写法 - 推荐 </button>
<button onClick = { this.change.bind( this ) }> 事件第三种写法 - 不推荐</button>
<button onClick = { this.change1 }> 事件第四种写法 - 推荐</button>
<button onClick = { this.eventHander }> 事件对象 </button>
<button onClick = { () => { this.argumentHandler( 10,20) } }> 事件传参 - 方法1 </button>
<button onClick = { this.argumentHandler.bind( this, 10 , 20 ) }> 事件传参 - 方法2 </button>
<Home fn = { this.transmitHandler }></Home>
</div>
);
}
}
export default App;
##处理用户输入
import React , { Component,Fragment } from 'react'
class Home extends Component {
inputHander = ( e ) => {
if( e.keyCode === 13 ){
console.log( e.target.value )
e.target.value = '请输入'
}
}
render () {
console.log( 'home', this )
return (
<Fragment>
<input onKeyUp= { this.inputHander } defaultValue = '请输入:'/>
<button onClick = { () => { this.props.fn( 10,20 ) } }> home- 事件 - 由父组件传递过来的 </button>
</Fragment>
)
}
}
export default Home