首页 > 解决方案 > 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>
        );
    }

}

标签: javascriptreactjsclassconstructor

解决方案


推荐阅读