将背景 url 作为道具传递给样式组件 [英] pass background url as prop to styled component

查看:29
本文介绍了将背景 url 作为道具传递给样式组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

//@flow从反应"导入反应;从'react-router-dom'导入{路由};从'../../components/grouping/Split'导入拆分;从'../../components/grouping/CenterBox'导入CenterBox;从样式组件"导入样式;类型道具 = {路线:数组<对象>,背景:字符串};出口默认({路线,背景}:道具)=>(

<Split push="right" alignItems="center" height={50} pad={{horizo​​ntal: 20 }}><div/><div>此功能即将推出!</div></拆分><DashboardContent background={background}><中心框><div style={{ transform: 'translateY(50%)' }}><CenterBox height={300} width={500} backgroundColor="#FFFFFF">此功能不包含在设计测试版中,很快就会推出</CenterBox>

</CenterBox></仪表盘内容>

);const DashboardContent = styled.div`背景: url(${props => props.background}) 无重复顶部中央;背景尺寸:100%;最小高度:100vh;`;

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

解决方案

将背景属性更改为返回字符串的函数将解决您的问题.

背景:${props =>`url(${props.background}) 无重复顶部中心`};

I have the following code:

// @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;
  `;

I would like to pass background as a prop to my styled component so that when it is passed a link to an image file it sets it as a background, the code compiles but the background does not show up. What am I doing wrong?

解决方案

Changing your background property to be a function that returns a string will fix your issue.

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

这篇关于将背景 url 作为道具传递给样式组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆