问题:
描述: 问题就是我这里将事件处理函数抽离封装到函数内了,然后当我在页面上点击 button 按钮后 功能不但没有实现 控制台还报了错
解决问题:
问题其实很容易理解,原因是因为 this指向的问题 , this指向是 undefined ,大概执行流程是这样的 <button onClick={this.amand}>点我修改state内值</button> 这里调用了 emand函数 然后是通过 this 反正就是 onClick={this.amand}> 这个 this是 undefined 然后 undefined.amand 这能不报错吗?
解决方法有三种分别 箭头函数 、bind 、Class实例
(1)箭头函数
class App extends React.Component {
state = {
name: '我是state内值'
}
// 封装函数 -- 抽离计算逻辑代码
amand () {
this.setState({
name: (this.state.name = '我被抽离计算逻辑修改了')
})
}
render () {
return (
<h1>
<p>state内值:{this.state.name}</p>
<button onClick={() => this.amand()}>点我修改state内值</button>
</h1>
)
}
}
描述: 这里是给 onClick={() => this.amand()} 这里加了箭头函数 因为箭头函数内没有 this , 箭头函数内 this 指向的是上一级
(2)bind
class App extends React.Component {
state = {
name: '我是state内值'
}
constructor () {
super()
this.name = this.name.bind(this)
}
// 封装函数 -- 抽离计算逻辑代码
amand () {
this.setState({
name: (this.state.name = '我被抽离计算逻辑修改了')
})
}
render () {
return (
<h1>
<p>state内值:{this.state.name}</p>
<button onClick={this.amand}>点我修改state内值</button>
</h1>
)
}
}
描述: 利用原型bind方法可以更改函数里面this的执行 所以可以在狗仔函数中调用 bind方法 ,然后把返回的值 赋值给 函数即可
(3)class实例方法
class App extends React.Component {
amand = () => {
this.setState({
name: this.state.name + 1
})
}
state = {
name: 1
}
render () {
return (
<h1>
<p>state内值:{this.state.name}</p>
<button onClick={this.amand}>点我修改state内值</button>
</h1>
)
}
}
说明:这里将 amand 普通函数修改了为 箭头函数 ,然后这样也解决了这个问题
描述: 将普通函数修改为箭头函数 其实也是利用了箭头函数的特点 来解决了 this 指向问题 虽然他是实验性的语法 但是直接使用就可以 因为脚手架内已经进行了相关 babel的配置 然后babel会自动转换成浏览器能够识别的方法