在 React 中导入目录

莫莉·克里斯蒂安

我在 src 中有一个组件目录,它有一个名为计算器的目录,然后它有 3 个不同的组件,而不是导入所有 3 个我想是否可以只导入目录计算器。

组件之一具有以下代码

 import React from 'react';
import {Textfit} from 'react-textfit';

const Screen = (props) => {
    return (
        <div className="screen--container">
          <Textfit
            max={40}
            throttle={60}
            mode="single"
            className="screen-top"
          >
            { props.expression }
          </Textfit>
          <Textfit
            max={150}
            mode="single"
            className="screen-bottom"
          >
            { props.total }
          </Textfit>
        </div>
      )
}

export default Screen;

然后在我的 App.js 中我有

import React, { Component } from "react";
import Calculator from "./components/calculator";
import "./App.css";

class App extends Component {
  render() {
    return (
      <div className="calculator--container">
        <Calculator.Screen {...this.props} />
        <Calculator.Keypad {...this.props} />
      </div>
    );
  }
}

export default App;

但目前它给了我一个错误如下 ./src/App.js Module not found: Can't resolve './components/calculator' in 'C:.....\react-simple-calculator\src'

我怎样才能使这项工作?

此外,开发人员的原始代码有

export default (props) => {
return ()}

但我已将其更改为

const Screen = (props) => { }
export default Screen;

对吗,第一个是什么意思?我指的代码是:https : //medium.com/@mazinosukah/lets-build-a-calculator-with-redux-and-react-using-tdd-6cb11946bad4

克里斯·坡

您不能以这种方式导入整个目录。如果您正在寻找更清洁的进口,请尝试以下操作:

进入您的calculator目录并创建一个index.js文件。然后,在该文件中导入所有 3 个组件并将它们导出为命名导出。

./components/calculator/index.js

import One from './One';
import Two from './Two';
import Three from './Three';

export { One, Two, Three };

然后,无论您在哪里需要使用组件,您都可以像这样导入它们

import { One, Two, Three } from './calculator';

您仍然需要一次单独导入它们。但是,如果您并不总是需要在单个目录中使用所有组件,这会使您的导入保持轻松。有时您不需要Two实例中的组件,因此您只需导入OneThree.

希望这可以帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章