开发中的时候,总是会写各种各样的事件,来实现去后台数据交互,页面之间的交互等!在react中事件的写法有很多种,当然这些写法的最终目的是一样的,只是在代码层面所展示的有些区别!下面总结一下,我所知道的事件的各种写法!(这里明确一点,react中事件都是使用的驼峰命名的规则)
第一种写法
第一种写法是使用箭头函数
import React, { Component } from 'react'
import ReactDom from 'react-dom'
class TestClick extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
}
handChangeText = (e) => {
this.setState({
inputValue: e.target.value
})
console.log(e);
}
render() {
return (
<div>
<input value={this.state.inputValue} onChange={this.handChangeText}></input>
</div>
)
}
}
export default TestClick;
第二种写法
使用js中的bind
方法来绑定this
的指向.
import React, { Component } from 'react'
import ReactDom from 'react-dom'
class TestClick extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
}
handChangeText (e) {
this.setState({
inputValue: e.target.value
})
console.log(e);
}
render() {
return (
<div>
<input value={this.state.inputValue} onChange={this.handChangeText.bind(this)}></input>
</div>
)
}
}
export default TestClick;
第三种写法
使用js中的bind
,在constructor
来绑定this
的指向.
import React, { Component } from 'react'
import ReactDom from 'react-dom'
class TestClick extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
this.handChangeText = this.handChangeText.bind(this)
}
handChangeText (e) {
this.setState({
inputValue: e.target.value
})
console.log(e);
}
render() {
return (
<div>
<input value={this.state.inputValue} onChange={this.handChangeText}></input>
</div>
)
}
}
export default TestClick;
第四种写法
使用简单函数的方法
import React, { Component } from 'react'
import ReactDom from 'react-dom'
class TestClick extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
}
handleChange(e) {
this.setState({
inputValue: e.target.value
})
}
render() {
return (
<div>
<input value={this.state.inputValue} onChange={(e) => this.handleChange(e)}></input>
</div>
)
}
}
export default TestClick;
第五种写法
使用匿名箭头函数直接实现(不推荐)
import React, { Component } from 'react'
import ReactDom from 'react-dom'
class TestClick extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
}
render() {
return (
<div>
<input value={this.state.inputValue} onChange={(e) =>{
this.setState({
inputValue: e.target.value
})
}}></input>
</div>
)
}
}
export default TestClick;
总结
这么多实现的方式,其实他们所做的事情是有同一个目的,就是解决this
的指向问题,在js
中,this
总是指向调用它的那个对象,为了使得this
指向的是我们需要它调用的对象,我们可以使用箭头函数和bind
来绑定this
的指向!
备注
react
中的事件是合成事件,将事件代理到document
上,然后进行统一分发!在react
中可以使用event.preventDefault()
阻止浏览器默认行为(例如标签不跳转)event.stopPropagation()
阻止冒泡(例如上级点击事件不生效)