mirror of
https://github.com/zhigang1992/create-react-app.git
synced 2026-04-23 04:40:23 +08:00
51 lines
1.7 KiB
Markdown
51 lines
1.7 KiB
Markdown
---
|
||
id: importing-a-component
|
||
title: Importing a Component
|
||
---
|
||
|
||
This project setup supports ES6 modules thanks to Webpack.<br>
|
||
While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead.
|
||
|
||
For example:
|
||
|
||
### `Button.js`
|
||
|
||
```js
|
||
import React, { Component } from 'react';
|
||
|
||
class Button extends Component {
|
||
render() {
|
||
// ...
|
||
}
|
||
}
|
||
|
||
export default Button; // Don’t forget to use export default!
|
||
```
|
||
|
||
### `DangerButton.js`
|
||
|
||
```js
|
||
import React, { Component } from 'react';
|
||
import Button from './Button'; // Import a component from another file
|
||
|
||
class DangerButton extends Component {
|
||
render() {
|
||
return <Button color="red" />;
|
||
}
|
||
}
|
||
|
||
export default DangerButton;
|
||
```
|
||
|
||
Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes.
|
||
|
||
We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`.
|
||
|
||
Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.
|
||
|
||
Learn more about ES6 modules:
|
||
|
||
- [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
|
||
- [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
|
||
- [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
|