简体   繁体   English

如何在 React 中导入 png 图像作为组件的背景?

[英]How do I import a png image as a background for a component in React?

The earth.png image is in the same folder as the src folder, the src folder contains various components. earth.png 图像与src src夹包含各种组件。 I have an app.js file in the main app folder which also contains the src folder.我在主 app 文件夹中有一个 app.js 文件,其中还包含src文件夹。 This is the component I have in the app.js file, I tried to import the earth.png file and use it as a background for the React MDL component but it didn't work.这是我在 app.js 文件中的组件,我尝试导入 earth.png 文件并将其用作 React MDL 组件的背景,但它不起作用。 Where am I going wrong?我哪里错了?


import React, {Component} from 'react';
import './App.css';
import {Layout, Header, Navigation, Drawer, Content} from 'react-mdl';
import Earth from './earth.png';
import Main from './components/main';
import { Link } from 'react-router-dom';

class App extends Component {
  render() {
  return (

<div style={{height: '300px', position: 'relative'}}>
    <Layout style={{background: 'source = {require{/earth.png}} center / cover'}}>
        <Header transparent title="Continental Coders" style={{color: 'black'}}>
            <Navigation>
                <a href="/aboutme">About me</a>
                <a href="/projects">Projects</a>
                <a href="/resume">Resume</a>
                <a href="/contact">Contact</a>
            </Navigation>
        </Header>
        <Drawer title="Title">
            <Navigation>
                <Link to="/aboutme">About Us</Link>
                <Link to="/projects">Projects</Link>
                <Link to="/resume">Resume</Link>
                <Link to="/contact">Contact</Link>
            </Navigation>
        </Drawer>
        <Content>
        <div className="page-content">
        <Main/>
        </div>
       </Content>
    </Layout>
</div>
);
}
}

export default App;







When you import the image, assuming you have the appropriate loaders, it's bringing in the file path, so you can use it like you would any other URL:当您导入图像时,假设您有适当的加载器,它会引入文件路径,因此您可以像使用任何其他 URL 一样使用它:

style={{ background: `url(${Earth})`}}

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

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