【问题标题】:How to import a File path in React Js?如何在 React Js 中导入文件路径?
【发布时间】:2018-01-12 06:18:41
【问题描述】:

我必须在我的 App.js 中导入多个文件。我的文件夹结构是

/src  
   /components       
     layout.js
   App.js  
   index.css
   index.js

这里我想从App.js 导入layout.js 文件。我的代码是

import React from 'react';
import Layout from './components/layout';

class App extends React.Component{
   render(){
       return ( 
          <div>
              <p>Hi</p>
          </div>
      );
   }
 }

 export default App;

在我的代码中,如何导入layout.js文件?

【问题讨论】:

  • import Layout from './components/layout';
  • 你已经导入了import Layout from './components/layout';
  • 但它不起作用

标签: javascript reactjs


【解决方案1】:

理想情况下,您的布局是一个组件,您可以简单地将其导入到 main.js 中。创建新组件时的一个很好的做法是在 components 文件夹中创建一个单独的文件夹并创建 index.js。通过这样做,您可以导入如下组件:

/src
/components
  /layout
    index.js
App.js
index.css
index.js



import React from 'react';
import Layout from './components/layout';

class App extends React.Component{
   render(){
       return ( 
          <div>
              <p>Hi</p>
              <Layout/>
          </div>
      );
   }
 }

 export default App;

【讨论】:

    【解决方案2】:

    看起来您正确导入了 Layout。如果它不起作用,也许您忘记在 layout.js 中export default Layout

    【讨论】:

      【解决方案3】:

      需要使用webpack的resolve.extensions来导入不以.js结尾的文件路径

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-05
        • 2019-03-31
        • 1970-01-01
        • 1970-01-01
        • 2013-11-04
        • 2021-03-02
        • 1970-01-01
        • 2023-04-05
        相关资源
        最近更新 更多