简体   繁体   English

为什么我不能从文件中导入 React 组件?

[英]Why can't I import a React component from a file?

I think I have written all the code right, but on the port I can only display app.js file我想我已经把所有的代码都写对了,但是在端口上我只能显示 app.js 文件

import React from 'react';

import ImgSlider from './ImgSlider';

import './App.css';

function App() {

return (

<div className="App" >
 
 <div className="book-box">
   <img src="" alt=""/>
   <div>
     <h1>Harry Potter</h1>
  </div>
 </div>
 
</div>
 );

 }

 export default App;

and I want to import div element from ImgSlider我想从ImgSlider导入 div 元素

import React from 'react';

function ImgSlider() {
 return (
    <div>
      <h3>Heading</h3>
      <p>Description</p>
      <img src="" alt=""/>
    </div>
  );
 }

   export default ImgSlider;

When i open browser it only shows HARRY POTTER from the App.js, I think it should also display div from the ImgSlider Console massage Line 3:8: 'ImgSlider' is defined but never used no-unused-vars当我打开浏览器时,它只显示 App.js 中的 HARRY POTTER,我认为它还应该显示来自 ImgSlider 控制台按摩行 3:8 的div :'ImgSlider' 已定义但从未使用过 no-unused-vars

Thanks for the attention谢谢关注

You arent rendering ImgSlider , just need to do this in App.js:你不是渲染ImgSlider ,只需要在 App.js 中做到这一点:

function App() {

return (

<div className="App" >
 
 <div className="book-box">
   <img src="" alt=""/>
   <div>
     <h1>Harry Potter</h1>
     /* ADD this code*/
     <ImgSlider />
  </div>
 </div>
 
</div>
 );

 }

This is just an example, you can add the <ImgSlider/> wherever you want.这只是一个例子,你可以在任何你想要的地方添加<ImgSlider/>

To render some content from imported component you have to render it like:要从导入的组件渲染一些内容,您必须像这样渲染它:

return (
<div className="App" >
 <div className="book-box">
   <img src="" alt=""/>
   <div>
     <h1>Harry Potter</h1>
     {/*Place it where you want to show it */}
     <ImgSlider />
  </div>
 </div>
</div>
 );
}

Simply add <ImgSlider /> into App只需将<ImgSlider />添加到 App

Your final code would look like this:您的最终代码如下所示:

import React from 'react';
import ImgSlider from './ImgSlider';
import './App.css';

function App() {
 return (

 <div className="App" >
 
  <div className="book-box">
    <img src="" alt=""/>
    <div>
      <h1>Harry Potter</h1>
      <ImgSlider />
   </div>
  </div>
 </div>
  );
}

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM