網站首頁 編程語言 正文
一、官網代碼
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 為了在回調中使用 `this`,這個綁定是必不可少的
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
二、官網解釋
你必須謹慎對待 JSX 回調函數中的?
this
,在 JavaScript 中,class 的方法默認不會綁定?this
。如果你忘記綁定?this.handleClick
?并把它傳入了?onClick
,當你調用這個函數的時候?this
?的值為?undefined
。這并不是 React 特有的行為;這其實與?JavaScript 函數工作原理有關。通常情況下,如果你沒有在方法后面添加?
()
,例如?onClick={this.handleClick}
,你應該為這個方法綁定?this
。
三、ES6 class
class Example {
constructor(a, b) {
this.a = a;
this.b = b;
console.log('Example');
}
sum() {
return this.a + this.b;
}
}
let exam1 = new Example(2, 1);
let exam2 = new Example(3, 1);
console.log(exam1.sum()); // 3
console.log(exam2.sum()); // 4
以上代碼可以看出es6中的class是不需要給方法單獨綁定this的
四、ES6 class不需要單獨綁定this,那為什么react中要單獨綁定this?
關鍵的一句話:當函數作為回調函數被調用時
onClick={this.handleClick} 就是將handleClick作為回調函數使用的
改造一下第三點的代碼,將exam1.sum和exam2.sum作為回調函數使用:
class Example {
constructor(a, b) {
this.a = a;
this.b = b;
}
sum() {
return this.a + this.b;
}
}
let exam1 = new Example(2, 1);
let exam2 = new Example(3, 1);
function getSum(cb) {
console.log('cb', cb());
}
getSum(exam1.sum)
getSum(exam2.sum)
此時代碼執行報錯:
Uncaught TypeError: Cannot read properties of undefined (reading 'a')
顯然 this 此時是undefined
五、作為回調函數時正確的代碼
class Example {
constructor(a, b) {
this.a = a;
this.b = b;
this.sum = this.sum.bind(this);
}
sum() {
return this.a + this.b;
}
}
let exam1 = new Example(2, 1);
let exam2 = new Example(3, 1);
function getSum(cb) {
console.log('cb', cb());
}
getSum(exam1.sum)
getSum(exam2.sum)
原文鏈接:https://blog.csdn.net/m0_47135993/article/details/126174562
- 上一篇:el-table多選+搜索
- 下一篇:for循環生成表單,表單校驗失效
相關推薦
- 2022-10-09 Python?pygame項目實戰監聽退出事件_python
- 2022-02-23 圖片返回base64數據渲染為圖片的處理
- 2022-08-13 Redis中String字符串sdshdr結構體的講解
- 2022-08-25 C#中的高效IO庫System.IO.Pipelines_C#教程
- 2023-10-30 docker拉取鏡像時報錯Error response from daemon: Head ““no
- 2022-11-24 Django?ORM?F對象和Q對象查詢_python
- 2022-08-28 ubuntu安裝samba文件共享
- 2022-04-14 Go語言context?test源碼分析詳情_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支