1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > React中this指向undefind???

React中this指向undefind???

时间:2018-12-12 11:53:33

相关推荐

React中this指向undefind???

1.有状态组件

有状态组件一般用来创建复杂数据的组件,包括页面UI的更新等,并且可以访问组件的生命周期方法

用法:大多数推荐利用Es6 Class field方法创建

class Clock extends ponent {constructor(props) {super(props);this.state = { date: new Date() };}render() {return (<div><h1>Hello, world!</h1><h2>It is {this.state.date.toLocaleTimeString()}.</h2></div>);}}

2.this的指向问题

先来看,我们在有状态组件中定义一个事件

import React from "react";export default class Capture extends ponent {constructor(props) {super(props)this.state = {value: 1}}handonClick() {const num = this.state.valuethis.setState({value: num++})}render() {return (<div><button onClick={this.handonClick}>点击</button><h1>{this.state.value}</h1></div>)}}

当我们点击事件的时候 num会进行加1 ,但是控制台打印结果令我们意想不到

我们在函数中打印一下this

handonClick() {// let num = this.state.value// console.log(this);// this.setState({//value: num+=1// })console.log(this);}

打印结果:

这是因为 jsx类的实例方法默认没有绑定this 所以此刻函数的作用域是由调用时决定的 所以此时this指向的是window 但是React在babel的转译 js会变成严格模式 所以会变成undefind

解决方法:

1.在构造函数中利用bind call apple方法绑定this

constructor(props) {super(props)this.state = {value: 1}this.handonClick = this.handonClick.bind(this)}

此刻可以发现解决啦 我们再来打印this 发现

2.使用箭头函数

<button onClick={()=>{this.handonClick()}}>点击</button><h1>{this.state.value}</h1>

因为箭头函数 没有单独的作用域 在函数内使用this,this会默认绑定函数外作用域上下文 此刻this指向的外围的this 我们测试一下

render() {console.log(this);return (<div><button onClick={()=>{this.handonClick()}}>点击</button><h1>{this.state.value}</h1></div>)}

无状态组件

不需要显示声明this关键字,在ES6的类声明中往往需要将函数的this关键字绑定到当前作用域,而因为函数式声明的特性,我们不需要再强制绑定。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。