【问题标题】:ReactJS ES6 Issue with import class导入类的 ReactJS ES6 问题
【发布时间】:2016-01-12 01:53:49
【问题描述】:

在 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 中),而且我在导入我制作的组件时没有问题,只有当我试图返回这个值时。我觉得我错过了一些非常简单的东西,我只是不知道是什么。有人可以帮忙吗?

【问题讨论】:

  • 您导出了 SomeName 吗?
  • 如果没有尝试将export default放在class SomeName前面
  • @AR7 我实际上只是这样做了,然后回来发布答案。那是我的问题。啊!
  • 哈哈不用担心。干得好自己弄清楚。
  • @doubleya 随意回答你自己的问题,它可能会在未来帮助别人

标签: javascript reactjs ecmascript-6


【解决方案1】:

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>
    )
}

【讨论】:

    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2017-02-13
    • 2017-11-22
    • 1970-01-01
    相关资源
    最近更新 更多