Javascript 如何使用由另一个组件使用的 ES6 在 React JS 中创建通用助手类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41949768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:45:55  来源:igfitidea点击:

how to create common helper class in React JS using ES6 which is used by another component?

javascriptoopreactjsecmascript-6

提问by nancy

I am a new in react js, my problem is I want to create a class which will work as global helper which I want to utilzed in another class or component.

我是 react js 的新手,我的问题是我想创建一个类作为全局助手,我想在另一个类或组件中使用它。

Use case for e.g First I want to fetch all resturant list keyword entered by user if user select any resturant then I want to get resturant details. in this use case I have to make two ajax call I want to create global ajax helper function which I can use in other components.

用例例如首先,如果用户选择任何餐厅,我想获取用户输入的所有餐厅列表关键字,然后我想获取餐厅详细信息。在这个用例中,我必须进行两次 ajax 调用,我想创建可以在其他组件中使用的全局 ajax 辅助函数。

class AjaxHelperClass{

    ResturantAPI(url){

        $.ajax({
            url : url,
            success : function(res){}
        });

    }
}

    export default AjaxHelperClass;

in my another component that use from my AjaxHelperClass function :

在我使用 AjaxHelperClass 函数的另一个组件中:

import React from 'react';
import {render} from 'react-dom';
import {AjaxHelperClass} from "./module/AjaxHelperClass"

class App extends React.Component {

    constructor(props) {
        super(props);

      ///  AjaxHelperClass.ResturantAPI(); // or
    let myajaxresult= new AjaxHelperClass(url);

    }

    render () {
        return(
        <p> Hello React!</p>
        );
    }
}

render(<App/>, document.getElementById('app'));

回答by patrick

Create a file called helpers.js

创建一个名为 helpers.js

//helpers.js

const AjaxHelper = (url) => {
    return (
      //ajax stuff here
    );
}

export default AjaxHelper;

Then in your component:

然后在您的组件中:

import React from 'react';
import {render} from 'react-dom';
import {AjaxHelper} from "./path/to/helpers.js"

class App extends React.Component {

    constructor(props) {
        super(props);
        let myajaxresult = AjaxHelper(url);
    }

    render () {
        return(
        <p> Hello React!</p>
        );
    }
}

回答by Saurabh Bayani

There is one more approach by wrapping it by a class rather than keeping all methods open and floating around utils.js

还有一种方法是将它包装在一个类中,而不是让所有方法保持开放和浮动 utils.js

//utilsjs
default export class Utils {
    static utilMethod = (data) => {
        return (
          //methods stuff here
        );
    }
}

and then in your component

然后在你的组件中

import React from 'react';
import {render} from 'react-dom';
import Utils from "./utils"

 class App extends React.Component {

    constructor(props) {
        super(props);
        let myData = {}; // any arguments of your
        Utils.utilMethod(myData);

    }

    render () {
        return(
        <p> Hello React!</p>
        );
    }
}

render(<App/>, document.getElementById('app'));

回答by Max Sindwani

The way that you've exported the class requires a new instance for each module you import it into. You can, instead, use a single instance as you've mentioned by exporting an instantiated AjaxHelperClass object rather than the class definition -- something like

您导出类的方式需要为您导入的每个模块创建一个新实例。相反,您可以通过导出实例化的 AjaxHelperClass 对象而不是类定义来使用您提到的单个实例——例如

export default new AjaxHelperClass();

This effectively gives you a global object. When importing the object, you can call its member functions i.e AjaxHelperClass.ResturantAPI();. Another option is to use staticmethods instead if all you want to use the class for is a namespace -- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

这有效地为您提供了一个全局对象。导入对象时,可以调用其成员函数,即AjaxHelperClass.ResturantAPI();. 另一种选择是使用静态方法,如果您只想使用该类的名称空间 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

回答by Joshua Pinter

Another way you can do it that doesn't involve you having to import specific helper methods is just by exporting an Objectin your helper file:

另一种不需要导入特定辅助方法的方法就是Object在辅助文件中导出一个:

Helpers.js

Helpers.js

export default { 

  connectToRestaurant: (url) => {

      $.ajax({
          url : url,
          success : function(res){}
      });

  },

  orderPizza: ( toppings = {} ) => {
    // Order a pizza with some sweet toppings.
  }

}

index.js

索引.js

import Helpers from "Helpers";

Helpers.connectToRestaurant( "http://delicious.com/" );

Helpers.orderPizza( { cheese: true, pepperoni: true } );

I think there might be a package size penalty by not specifically including the functions from the modules, but the convenience factor, in my opinion, can often outweigh that penalty.

我认为不特别包含模块中的功能可能会对包大小造成损失,但在我看来,便利因素通常可以超过这种损失。