React事件
1.通过onXxx属性指定事件处理函数(注意大小写)
- React使用的是自定义(合成)事件,而不是使用的原生DOM事件
- React中的事件是通过事件委托方式处理的(委托给组件最外层的元素) 2.通过event.target得到发生事件的DOM元素对象
事件绑定
- 在无状态组件怎么绑定事件??----现多用的
function Child1 () {
function click (argus) {
console.log('argus', argus)
console.log('子组件点击事件')
}
return (
<div>
<p>这是子组件</p>
<button onClick = {() => click(1)}>子组件点击</button>
</div>
)
}
- 在类组件中怎么绑定事件??
class Child2 extends React.Component{
click (argus) {
console.log('class组件点击事件')
console.log('this', this)
console.log('argus', argus)
}
render () {
this.handle = this.click.bind(this, 1)
return (
<div>
<p>class组件</p>
{/* 1.直接绑定事件,需要通过bind 绑定this,并通过bind传递参数 */}
<button onClick = {this.click.bind(this, 1)}>class组件点击1</button>
{/* 2.有额外的参数时,可以通过箭头函数,还可以传递参数,且无需绑定this */}
<button onClick = {() => this.click(11)}>class组件点击2</button>
{/* 3.先通过赋值并改变this指向 */}
<button onClick = {this.handle}>class组件点击3</button>
</div>
)
}
}