Javascript 如何使用 React JS 导出多个类组件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50073105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:33:02  来源:igfitidea点击:

How do I export more than one class component with React JS?

javascriptreactjsfunctioncomponentses6-class

提问by Tony Carbetta

I'm new to React and would like to keep all my components in one file. How do I export more than one component and keep them in the same file?

我是 React 的新手,希望将所有组件保存在一个文件中。如何导出多个组件并将它们保存在同一个文件中?

    import React, { Component } from "react";

class MyText extends Component {
  render() {
    return (<div>
      <h1>
        Component</h1>
      <p>This class component is named MyText. I can re-use it's code by simply Rendering (fancy name for calling) it by it's class name and I won't have to re type it, however many times I will need it.</p>
    </div>);
  };
}

class GreetName extends Component {
  render() {
    return (
      <div>
       <h1>Hello, {this.props.name}</h1>;
       </div>
    );
  };
}

export default MyText;

回答by Denys Kotsur

You can do as Jess Kenneysaid or use naming export at the bottom of your file:

您可以按照Jess Kenney所说的去做,或者在文件底部使用命名导出:

SomeComponent.js

一些组件.js

import React, { Component } from "react";

class MyText extends Component {
  render() {
    return (<div>
      <h1>
        Component</h1>
      <p>This class component is named MyText. I can re-use it's code by simply Rendering (fancy name for calling) it by it's class name and I won't have to re type it, however many times I will need it.</p>
    </div>);
  };
}

class GreetName extends Component {
  render() {
    return (
      <div>
       <h1>Hello, {this.props.name}</h1>;
       </div>
    );
  };
}

export { MyText, GreetName };

And then use it like:

然后像这样使用它:

import { MyText, GreetName } from './SomeComponent'

I advice you to use one component per file, so you can keep your project modular. In ReactJSit's a convention to export one component from a file, and to export it is as the default export.

我建议您为每个文件使用一个组件,这样您就可以保持项目模块化。在ReactJS它从文件导出一个组件,并导出它作为默认出口的约定。

If it's helper component which used only in the particular you can put it to the same file as functional component.

如果它是仅用于特定的辅助组件,您可以将其与功能组件放在同一文件中。

回答by Jess Kenney

Instead of using the export defaultline at the bottom, you can put export before each class definition, like export class GreetName...then to include your classes in another file you can use import {MyText, GreetName} from 'your/file.js'

export default您可以将导出放在每个类定义之前,而不是使用底部的行,就像export class GreetName...将您的类包含在您可以使用的另一个文件中一样import {MyText, GreetName} from 'your/file.js'