javascript - React - React 类中的函数
问题描述
我很难理解为什么反应中的类与普通 js 的功能不同。还是我错过了什么?
在我拥有的代码中,我知道 Header 继承了“props”的属性,因此感谢构造函数,我可以在 jsx 中使用 this.name。还有,在标题中。proto驻留在函数 doSomething 中。但是当我调用函数 doSomething 时,可以调用该函数但无法访问“this.name”。在普通的 js 中,它会起作用。发生什么了?
为什么绑定/使用箭头函数可以解决问题?
提前致谢!
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export class Header extends Component {
constructor(props) {
super();
this.name = props.name;
}
doSomething() {
this.name = 5;
}
render() {
return(
<div>
<button onClick={this.doSomething}></button>
</div>
);
}
}
解决方案
推荐阅读
- c++ - 将浮点数格式化为带有可选小数点的有限大小的 char 数组
- jestjs - 开玩笑:如何模拟一个只是布尔值的变量?
- javascript - 尝试根据同一行上另一个单元格的值变化擦除相应的单元格内容
- javascript - JavaScript中的require()函数不起作用
- mysql - MySQL - 在另一列上使用 DATEADD 更新列
- sql - 从 DEMO_ORDER_ITEMS 中选择 ORDER_ITEM_ID、PRODUCT_ID,其中 TOTAL_PROFIT >=,300?
- python-3.x - 如何通过 dm 的 Discord.py Rewrite 进行嵌入
- asp.net-web-api - 可以使用客户端登录,但不能发出 API 请求。401
- swift - 无法使用带有 pre-iOS 14 目标的 UIDocumentPickerViewController 选择预注册的文件类型
- sql - 通过几个步骤从一个表汇总到另一个表