react事件处理函数中绑定this的bind()函数
生活随笔
收集整理的這篇文章主要介紹了
react事件处理函数中绑定this的bind()函数
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
問(wèn)題引入
import React, { Component } from 'react'; import {Text,View } from 'react-native';export default class App extends Component<Props> {constructor(props){super(props)this.state={times:0}this.timePlus=this.timePlus.bind(this);}timePlus(){let time=this.state.timestime++this.setState({times:time})}render() {return (<View><Text onPress={this.timePlus}>有本事點(diǎn)我呀</Text>//<Text onPress={this.timePlus.bind(this)}>有本事點(diǎn)我呀</Text>
<Text>你點(diǎn)了我{this.state.times}次</Text> </View>
);
}
}
每次在處理事件函數(shù)時(shí)都需要綁定this的bind函數(shù);
?
bind() 最簡(jiǎn)單的用法是創(chuàng)建一個(gè)函數(shù),使這個(gè)函數(shù)不論怎么調(diào)用都有同樣的 this 值。
bind()方法會(huì)創(chuàng)建一個(gè)新函數(shù),當(dāng)這個(gè)新函數(shù)被調(diào)用時(shí),它的this值是傳遞給bind()的第一個(gè)參數(shù), 它的參數(shù)是bind()的其他參數(shù)和其原本的參數(shù).?
this.x = 9; var module = {x: 81,getX: function() { return this.x; } };module.getX(); // 返回 81 var retrieveX = module.getX; retrieveX(); // 返回 9, 在這種情況下,"this"指向全局作用域// 創(chuàng)建一個(gè)新函數(shù),將"this"綁定到module對(duì)象 var boundGetX = retrieveX.bind(module); boundGetX(); // 返回 81?
從實(shí)例可以看出:React構(gòu)造方法中的bind會(huì)將handleClick函數(shù)與這個(gè)組件Component進(jìn)行綁定以確保在這個(gè)處理函數(shù)中使用this時(shí)可以時(shí)刻指向這一組件。
?
源碼地址:https://github.com/zuobaiquan/react-native/tree/master/myExercise/firstProject
轉(zhuǎn)載于:https://www.cnblogs.com/zuobaiquan01/p/8728949.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的react事件处理函数中绑定this的bind()函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 检查男人不育到驻马店哪家医院好
- 下一篇: Chrome无法播放m3u8格式的直播视