从 JavaScript 文件导出函数

Export a function from a JavaScript file

我正在尝试在 React 中创建一个只是函数的组件

import React from "react";

function TableSortFunction(data, method, column) {
  const newList = [];
  for (let i; i <= data.length; i++) {
    newList.push(data[i].column);
  }
  console.log(newList), data, method, column;
  return newList;
}

export default TableSortFunction;

我正在像这样在另一个组件中导入我的函数

import { TableSortFunction } from "./TableSortFunction";

但我收到一条错误消息:

Attempted import error: 'TableSortFunction' is not exported from './TableSortFunction'.

如何导出一个只是函数的js文件?

由于您将其导出为默认值,因此您必须像这样导入它:

import TableSortFunction from "./TableSortFunction";

编辑:您的代码的另一个问题是以下语法不正确。

console.log(newList), data, method, column;

试试这个:

console.log(newList, data, method, column);

试试这个

import TableSortFunction from "./TableSortFunction";

Your console isn't correct

而不是

console.log(newList), data, method, column;

应该是

console.log(newList, data, method, column);

有两种类型的导入 - 命名和默认。

导出和导入功能

导出自 - say.js

function sayHi(user) {
  alert(`Hello, ${user}!`);
}

function sayBye(user) {
  alert(`Bye, ${user}!`);
}

export {sayHi, sayBye};

从 - say.js 导入到 main.js

import {sayHi, sayBye} from './say.js';

sayHi('John'); // Hello, John!
sayBye('John'); // Bye, John!

为了更好的理解,可以参考文章