首页 > 解决方案 > 在 ReactJS 中导出 Object.prototype.functions

问题描述

如何将此方法导出到另一个 React 组件?

  // utils.js 

   Array.prototype.last_element = function() {
       const last_index = this.length-1;
       return this[last_index];
    };

    export default ... ? 
  // main.jsx

  import ... ? from './utils.js';
  
  const arr = [1 , 2 , 3];

  console.log(arr.last_element());

标签: javascriptarraysreactjsobjectbabeljs

解决方案


你不需要导出。只需在 main.jsx 中导入文件即可。

// main.jsx
import "./utils.js";

但是,由于您使用的是 React,因此您只需在 App.tsx 或 index.tsx 中导入 utils.js 一次,因为您的主要目的是定义 Array 原型。


推荐阅读