【问题标题】:How do I export more than one class component with React JS?如何使用 React JS 导出多个类组件?
【发布时间】:2018-10-08 22:20:43
【问题描述】:

我是 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;

【问题讨论】:

标签: javascript reactjs function components es6-class


【解决方案1】:

您可以按照 Jess Kenney 所说的进行操作,也可以在文件底部使用命名导出:

SomeComponent.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 };

然后像这样使用它:

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

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

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

【讨论】:

  • 哇,真的吗?看起来它会有很多额外的文件。我仍然不明白为什么,但我只是对 React 感到困惑,所以我相信我以后在制作更大的应用程序时会遇到一个原因。
  • @TonyCarbetta 是的。遵循Single responsibility 原则,理想情况下,每个组件都应该只做一件事。如果它最终增长,它应该被分解成更小的子组件。您可以阅读文档中的this 文章,也许它可以帮助您理解。
【解决方案2】:

除了使用底部的 export default 行之外,您可以将 export 放在每个类定义之前,例如 export class GreetName... 然后将您的类包含在另一个文件中,您可以使用 import {MyText, GreetName} from 'your/file.js'

【讨论】:

  • 听起来不错!我也是堆栈溢出的新手,我该如何结束这个问题并给予你信任?
  • 不要关闭问题并将其标记为已接受的答案。
【解决方案3】:
export default secretContext;
export {taskData};

【讨论】:

    【解决方案4】:

    用于导出两个功能组件

    在 app.js 中执行此操作

    export default App;
    export{New_component};
    

    在 index.js 中执行此操作

    import App from './App';
    import {Hari} from './App';
    
    <App  name={people.name}/>
    <New_component msg={people.msg}/>
      
    

    确保组件名称以大写字母开头

    【讨论】:

      猜你喜欢
      • 2020-10-02
      • 2021-04-28
      • 2018-07-12
      • 1970-01-01
      • 2018-10-12
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      相关资源
      最近更新 更多