How to create helper file full of functions in react native?

后端 未结 6 750
悲哀的现实
悲哀的现实 2020-12-04 06:48

Though there is a similar question I am failing to create a file with multiple functions. Not sure if the method is already outdated or not as RN is evolving very fast. How

6条回答
  •  星月不相逢
    2020-12-04 07:21

    To achieve what you want and have a better organisation through your files, you can create a index.js to export your helper files.

    Let's say you have a folder called /helpers. Inside this folder you can create your functions divided by content, actions, or anything you like.

    Example:

    /* Utils.js */
    /* This file contains functions you can use anywhere in your application */
    
    function formatName(label) {
       // your logic
    }
    
    function formatDate(date) {
       // your logic
    }
    
    // Now you have to export each function you want
    export {
       formatName,
       formatDate,
    };
    

    Let's create another file which has functions to help you with tables:

    /* Table.js */
    /* Table file contains functions to help you when working with tables */
    
    function getColumnsFromData(data) {
       // your logic
    }
    
    function formatCell(data) {
       // your logic
    }
    
    // Export each function
    export {
       getColumnsFromData,
       formatCell,
    };
    

    Now the trick is to have a index.js inside the helpers folder:

    /* Index.js */
    /* Inside this file you will import your other helper files */
    
    // Import each file using the * notation
    // This will import automatically every function exported by these files
    import * as Utils from './Utils.js';
    import * as Table from './Table.js';
    
    // Export again
    export {
       Utils,
       Table,
    };
    

    Now you can import then separately to use each function:

    import { Table, Utils } from 'helpers';
    
    const columns = Table.getColumnsFromData(data);
    Table.formatCell(cell);
    
    const myName = Utils.formatName(someNameVariable);
    

    Hope it can help to organise your files in a better way.

提交回复
热议问题