在 React 中从另一个文件导入变量
Import Variables from another file in React
在 React 中从另一个文件导入变量:
- 从文件中导出变量
A
,例如export const str = 'hello world'
。 - 将文件中的变量导入
B
为import {str} from './another-file'
.
下面是从一个名为
another-file.js
.
// 👇️ named export export const str = 'Hello world'; // 👇️ named export export const num = 42;
以下是我们如何将变量导入名为App.js
.
// 👇️ named imports import {str, num} from './another-file'; export default function App() { return ( <div> <h2>Str is: {str}</h2> <hr /> <h2>Num is: {num}</h2> </div> ); }
如果必须,请确保更正指向another-file.js
模块的路径。上面的示例假定another-file.js
和App.js
位于同一目录中。
For example, if another-file.js
was located one directory up, you’d have to
import as import {str} from '../another-file'
.
The syntax we’re using to export and import variables is called
JavaScript modules.
The example above uses a named export and a named import.
The main difference between named and default exports and imports is – you can
have multiple named exports per file, but you can only have a single default
export.
Let’s look at an example of how we would import a variable that was exported
using a default export.
const str = 'Hello world'; // 👇️ default export export default str;
And here is how we would import the variable using a default import.
// 👇️ default import import str from './another-file'; export default function App() { return ( <div> <h2>Str is: {str}</h2> </div> ); }
Notice that we didn’t wrap the import in curly braces.
We could have also used a different name when importing the variable, e.g.
fooBar
.
// 👇️ default import import fooBar from './another-file'; export default function App() { return ( <div> <h2>Str is: {fooBar}</h2> </div> ); }
This works, but is confusing and should be avoided.
If you are exporting a variable (or an arrow function) as a default export, you
have to declare it on 1 line and export it on the next. You can’t declare and
default export a variable on the same line.
You also don’t have to think about which members are exported with a default or named export.
You can also mix and match. Here is an example of a file that uses both a
default and a named export.
const str = 'Hello world'; // 👇️ default export export default str; // 👇️ named export export const num = 42;
这是导入这两个变量的方法。
// 👇️ default and named imports import str, {num} from './another-file'; export default function App() { return ( <div> <h2>Str is: {str}</h2> <hr /> <h2>Num is: {num}</h2> </div> ); }
我们使用默认导入来导入str
变量,使用命名导入来导入num
变量。
请注意,每个文件只能有一个默认导出,但您可以根据需要拥有任意多个命名导出。