React 事件绑定
事件的绑定
在JSX中,对事件进行了再次的封装,绑定事件的写法有些许不同,JSX中事件的绑定使用驼峰命名法
事件名 | 写法 |
---|---|
点击 | onClick |
改变 | onChange |
。。。 | 。。。 |
代码的编写
class Weather extends React.Component{
constructor(props){
super(props)
this.state = {
isHot:false
}
}
render(){
// 读取状态
const {isHot} = this.state
return <h1 onClick={this.changeWeather}>今天的天气很{isHot ? '炎热' : '凉爽'}</h1>
}
// 事件回调函数
changeWeather(){
// 由于changeWeather是作为onClick的回调,所以不是通过实例调用的,始直接调用的
// 类中的方法默认开启局部的严格模式,所有changeWeather中的this为undefined
console.log(this)
}
}
}
处理this指向问题
改变this的指向
this.changeWeather = this.changeWeather.bind(this)
class Weather extends React.Component{
constructor(props){
super(props)
this.state = {
isHot:false
}
this.changeWeather = this.changeWeather.bind(this)
}
render(){
// 读取状态
const {isHot} = this.state
return <h1 onClick={this.changeWeather}>今天的天气很{isHot ? '炎热' : '凉爽'}</h1>
}
// 事件回调函数
changeWeather(){
// 由于changeWeather是作为onClick的回调,所以不是通过实例调用的,始直接调用的
// 类中的方法默认开启局部的严格模式,所有changeWeather中的this为undefined
console.log(this)
}
}
}
解析:
- bind()改变函数调用的this,并返回一个新函数
- changeWeather()方法位于Weather原型对象上,而不是在实例上,
this.changeWeather
是通过原型链查找得到的this.changeWeather = this.changeWeather.bind(this)
,将changeWeather
回调函数置于Weather实例上
使用箭头函数
class Weather extends React.Component{
constructor(props){
super(props)
this.state = {
isHot:false
}
}
render(){
// 读取状态
const {isHot} = this.state
return <h1 onClick={() => {this.setState({isHot:!this.state.isHot})}}>今天的天气很{isHot ? '炎热' : '凉爽'}</h1>
}
}
ReactDOM.render(<Weather/>,document.querySelector('#root'))
class Weather extends React.Component{
constructor(props){
super(props)
this.state = {
isHot:false
}
this.changeWeather = this.changeWeather.bind(this)
}
render(){
// 读取状态
const {isHot} = this.state
return <h1 onClick={this.changeWeather}>今天的天气很{isHot ? '炎热' : '凉爽'}</h1>
}
// 事件回调函数
changeWeather = () =>{
console.log(this)
}
}
}
在class中,
a = b
,那么a属性
位于类的实例上的changeWeather = () =>{ console.log(this) }
解析:将回调函数写成箭头函数的形式,主要原因是可以忽略调用的this指向,向外寻找this,那么这个this就变为组件实例
阻止默认事件
在 React 中另一个不同点是你不能通过返回 false
的方式阻止默认行为。你必须显式的使用 preventDefault
。
例如,传统的 HTML 中阻止表单的默认提交行为,你可以这样写:
<form οnsubmit="console.log('You clicked submit.'); return false">
<button type="submit">Submit</button>
</form>
在React中则是这么写的e.preventDefault
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log('You clicked submit.');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}