如何将图像传递给样式化的组件?

时间:2019-06-01 11:33:54

标签: reactjs styled-components

我在styled-components中使用ReactJS,并且试图创建一个可以将background-image作为道具的组件。经过研究,我已经尝试过了:

import SpeechBubble1 from '../images/home_images/Speech 1.png';
...

const SpeechBubble = styled.div`
    background-image: url(${props => props.background});
`;

...

<SpeechBubble background={SpeechBubble1} />

但是它不起作用。在浏览器元素窗口中检查,可以看到我得到了Invalid property value的{​​{1}}。

我在做什么错了?

编辑: 我也尝试这样做,但没有成功:

background-image

3 个答案:

答案 0 :(得分:0)

您可以使用内联样式:

<SpeechBubble style={{background: `url(${SpeechBubble1})`}} />

答案 1 :(得分:0)

请确保为样式化的组件包括一个height,否则它将不会显示任何内容(除非它具有定义其尺寸的子项)。

工作示例

Edit Styled Components - Background Image


组件/容器

import styled from "styled-components";

const Container = styled.div`
  height: 100vh;
  background-image: url(${({ background }) => background});
  background-repeat: no-repeat;
  background-size: cover;
`;

export default Container;

index.js

import React, { Fragment } from "react";
import { render } from "react-dom";
import reactbg from "./images/reactbg.png";
import Container from "./components/Container";
import GlobalStyles from "./components/GlobalStyles";
import Title from "./components/Title";

const App = () => (
  <Fragment>
    <GlobalStyles />
    <Container background={reactbg}>
      <Title>Hello World</Title>
    </Container>
  </Fragment>
);

render(<App />, document.getElementById("root"));

答案 2 :(得分:0)

Index.js

    import React from 'react'
    import {ProfilePic} from './NavigationElements'
    import profileimg from '../../images/profileimg.jpg'

    const Navigation = () => {
      return (
      <NavigationWrapper>
        <ProfilePic src={profileimg} alt="" />
      </NavigationWrapper>
      )
     }

     export default Navigation

NavigationElements.js

    import styled from "styled-components";

    export const NavigationWrapper = styled.div`
     color: #fff;
    `
    export const ProfilePic = styled.img`
     width: 5vh;
     height: 3vh;
     margin: 55px;
    `