import export
import React, { Component } from 'react';
表示React是default导出的,Component是命名导出的。
如何导出类
单文件导出1
// Module.js
class ModuleA {}
class ModuleB {}
export default ModuleA;
export { ModuleB };
// demo.js
import ModuleA, { ModuleB } from './Module';
单文件导出2
// Module.js
class ModuleA {}
class ModuleB {}
class Module {}
Module.A = ModuleA;
Module.B = ModuleB;
export default Module;
// demo.js
import Module from './Module';
const {A, B} = Module;
多文件导出1
// CoreModule.js
export { default as EventManager } from './EventManager';
export { default as AccountManager } from './AccountManager';
// demo.js
import { EventManager, AccountManager } from './CoreModule';
多文件导出2
// CoreModule.js
import AccountManager from './AccountManager';
import EventManager from './EventManager';
export { EventManager, AccountManager }
// demo.js
import { EventManager, AccountManager } from './CoreModule';
单例
import EventEmitter from 'EventEmitter';
class EventManager {
static sInstance = null;
constructor() {
this._eventEmitter = new EventEmitter();
}
addListener(eventName, callback) {
if (typeof callback !== 'function') {
throw new TypeError('listener argument must be a function');
}
this._eventEmitter.addListener(eventName, callback);
}
removeListener(eventName, callback) {
if (typeof callback !== 'function') {
throw new TypeError('listener argument must be a function');
}
this._eventEmitter.removeListener(eventName, callback);
}
removeAllListeners() {
this._eventEmitter.removeAllListeners();
}
triggerEvent(eventName, ...args) {
this._eventEmitter.emit(eventName, args);
}
static getInstance() {
if (!EventManager.sInstance) {
EventManager.sInstance = new EventManager();
}
return EventManager.sInstance;
}
}
EventManager.EventAccount = "account";
export default EventManager;