ReactJS ES6导入类问题

ReactJS ES6 Issue with import class

本文关键字:问题 导入 ES6 ReactJS      更新时间:2023-09-26

在ReactJS中,我试图做一些非常简单的事情。我创建了一个类:

//SomeName.js
class SomeName {
    constructor(name){
        this.name = name;
    }
}

在我的React.component中,我有:

//Index.js
import React from 'react'
import SomeName from './parts/SomeName'
class Index extends React.Component{
    constructor(){
        super();
        let newName = new SomeName("John Doe");
        this.getName = this.getName.bind(this);
    }
    getName(){
        return newName;
    }
    render() {
        return (
            <div className="pages-container">
                Hello {this.getName}
            </div>
        )
    }
};

然而,我在Index.js构造函数中添加了一个调试器,没有引用SomeName。我看到的每一个引用都表明它是这样做的(但不是在ReactJS中),而且我在导入我制作的组件时没有问题,只有当我试图返回这个值时。我觉得我错过了一些非常简单的东西,我只是不知道是什么。有人能伸出援手吗?

1)将newName定义为局部变量。要使其在getName中可访问,应将其分配到this:

constructor() {
    super();
    this.newName = new SomeName("John Doe"); // fixed here
    this.getName = this.getName.bind(this);
}
getName(){
    return this.newName; // and here
}

2) 您应该在render方法中调用getName。否则你会得到函数,而不是结果:

render() {
    return (
        <div className="pages-container">
            Hello {this.getName()} //do not forget parentheses
        </div>
    )
}