如何在另一个类中创建导入类的实例

时间:2016-07-05 06:08:17

标签: javascript reactjs ecmascript-6 es6-module-loader

user.js的

class User {

  constructor() {
    this.fisrtName
    this.lastName
  }

  get fullName() {
    `${this.firtName} ${this.lastName}`
  }

}

export default User

Test.js

import React from 'react'
import {User} from './User'

class Test extends React.Component {

  testClick(e) {
    const user = new User() //error! because User is undefined.
  }

  render() {
    return (
      <button onClick={this.testClick.bind(this)}>test</button>
    )
  }

}

export default Test

1 个答案:

答案 0 :(得分:4)

更改

import {User} from './User'

import User from './User'

您的错误是您在 User.js 模块内部进行默认导出export default User,但在 Test.js 命名导入:import {User} from './User'