简体   繁体   中英

Import vanilla ES6 extended class into React

How do I import vanilla ES6 classes and extended classes into a ReactJS project without using React.Component ?

App.js

import React from 'react';
import {Log} from './lib/Log';
import {CoolLog} from './lib/CoolLog';
import {HotLog} from './lib/HotLog';

class App extends React.Component {
    constructor() {
        ...
    }
    doLog() {
        var coolLog = new CoolLog();
        coolLog.log('Cool!');
        var hotLog = new HotLog();
        hotLog.log('Hot!');
    }
    render() {
        ...
    }
}

export default App;

lib/Log.js

export class Log {
    _log(data){
      console.log(data);
    }
}

lib/CoolLog.js

import {Log} from './lib/Log';

export class CoolLog extends Log {
    log(data){
      this._log('❄️'+data+'❄️');
    }
}

lib/HotLog.js

import {Log} from './lib/Log';

export class HotLog extends Log {
    log(data){
      this._log('🔥'+data+'🔥');
    }
}

When you want to import it you have to export it first:

export class Log {
    _log(data){
      console.log(data);
    }
}

You are importing Log but using _log . _log is not defined anywhere. Use this._log instead. When you extend some class, you can use the methods of that parent class using this .

Here, it works perfectly.

export class CoolLog extends Log {
    log(data){
        this._log('❄️'+data+'❄️');
    }
}

在此处输入图片说明

Learn more about extends here .

My sample did not illustrate the structure the class files (stored in a lib directory) which was where the problem lied.

lib/CoolLog.js and lib/HotLog.js should import ./Log.js and not lib/Log.js since it is in the same folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM