简体   繁体   English

在Reacjs中导入另一个(帮助器)类

[英]import another (helper) class in Reacjs

I want to write a helper class for like: 我想写一个像这样的助手类:

export default class A {
  constructor() {
    console.log(1);
  }
  test() {
    console.log(2);
  }
}

that I can use it in my component: 我可以在我的组件中使用它:

import React, { Component } from "react";
import A from "./service/socket";

class Test extends Component {
  state = {
    counter: 0
  };

  componentDidMount = () => {
    A.test();
  };
}

how can I do that? 我怎样才能做到这一点?

test is a method on an instance of A . test是对A 实例A If you just want to create a collection of helper functions and don't actually need a class , export the functions directly from the module: 如果您只想创建一个辅助函数集合,而实际上不需要一个 ,则直接从模块中导出函数:

// ./service/socket
export function test() {
  console.log(2);
}

// somefile.js
import {test} from './service/socket';
test();

If you really need a class, you'd have to create an instance first, eg 如果您确实需要一个类,则必须首先创建一个实例,例如

import React, { Component } from "react";
import A from "./service/socket";

const instanceA = new A();

class Test extends Component {
  state = {
    counter: 0
  };

  componentDidMount = () => {
    instanceA.test();
  };
}

But you shouldn't use classes as bags of methods. 但是您不应该将类用作方法包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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