【问题标题】:How can I use React style imports for my own files?如何为我自己的文件使用 React 样式导入?
【发布时间】:2021-12-27 01:08:55
【问题描述】:

我想使用 React 或本示例中经常使用的这种形式 react-redux

import redux, { useSelector, useDispatch } from 'react-redux';

所以我尝试了明显的:

我创建了一个导出文件:

const exp = {};
exp.a = 'a-1';
exp.b = 'b-1'; 
export default exp;

还有一个要导入的文件:

import {a, b} from './40-export.js';  // this does not work
// import test from './40-export.js';  // this works
// const {a, b} = test;  // this works

【问题讨论】:

  • 您似乎混淆了命名导入和对象解构。不要导出对象,而是使用export const a = 'a-1'

标签: javascript reactjs import export


【解决方案1】:

您需要同时拥有export default 和命名导出。制作独立的 ab 变量以供您导出,并分配给默认导出对象的属性。

export const a = 'a-1';
export const b = 'b-1'; 
export const exp = { a, b }; // if you want this to be a named export too
export default exp;

【讨论】:

  • ... 所以我可以使用这个表格 .... import defaultExport, { export1 [ , [...] ] } from "module-name"; 正如我在 MDN 上看到的那样 ...developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… ... 我会试一试 ... 有效。 ..
  • @user17331023 所以需要注意的是,import { thing } from 'blah' 没有破坏。
  • @evolution ...那你怎么称呼它? “命名导入”奇怪的是使用相同的语法。
  • @user17331023 yes, exactly。语法很相似,这就是为什么它会让人绊倒,包括我自己。
【解决方案2】:
export const a = 2
export const b = 3
export default const c = 3

然后

import c , {a, b} from "your/file"

注意{...} 用于命名导入,而没有它用于默认导出。

【讨论】:

    猜你喜欢
    • 2018-02-22
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2018-03-15
    • 2020-09-18
    相关资源
    最近更新 更多