将背景url作为prop样式传递给样式组件

时间:2017-08-25 07:25:39

标签: reactjs styled-components

我有以下代码:

// @flow
import React from 'react';
import { Route } from 'react-router-dom';
import Split from '../../components/grouping/Split';
import CenterBox from '../../components/grouping/CenterBox';
import styled from 'styled-components';

type Props = {
  routes: Array<Object>,
  background: String
};


export default ({ routes, background }: Props) =>
  (<div>
    <Split push="right" alignItems="center" height={50} pad={{ horizontal: 20 }}>
      <div />
      <div>This feature will be available soon!</div>
    </Split>
    <DashboardContent background={background}>
      <CenterBox>
        <div style={{ transform: 'translateY(50%)' }}>
          <CenterBox height={300} width={500} backgroundColor="#FFFFFF">
            This feature is not included as part of the design beta and will be available soon
          </CenterBox>
        </div>
      </CenterBox>
    </DashboardContent>
  </div>);



  const DashboardContent = styled.div`
  background: url(${props => props.background}) no-repeat top
      center;
    background-size: 100%;
    min-height: 100vh;
  `;

我想将背景作为道具传递给我的样式组件,以便在传递图像文件的链接时将其设置为背景,代码编译但背景不会显示。我究竟做错了什么?

2 个答案:

答案 0 :(得分:4)

将background属性更改为返回字符串的函数将解决您的问题。

background: ${props => `url(${props.background}) no-repeat top center`};

答案 1 :(得分:0)

这行得通吗?

 const DashboardContent = styled.div`
  background: url(${props => props.background}) no-repeat top center;
 `

 <DashboardContent background={`https://xxxx/xxxx${background}`}/>