简体   繁体   English

带有样式组件的动态背景图像

[英]Dynamic background image with styled-components

I've been struggling with making this work, I have a prop called weather, it's value can be either Drizzle, Cloudy or any other type of Text.我一直在努力完成这项工作,我有一个名为天气的道具,它的值可以是毛毛雨、多云或任何其他类型的文本。

I have images imported on the top (only two at the moment), I've tried with我在顶部导入了图像(目前只有两个),我尝试过

background-image: url(${weather => (weather === 'Drizzle) ? Drizzle : Cloudy})

But it won't work, it will always go with Cloudy (false), I may need to make a nested ifs or ternary operators but at the moment I would like to get it working with two at least.但它不会工作,它总是 go 和多云(假),我可能需要做一个嵌套的 ifs 或三元运算符,但目前我想让它至少与两个一起工作。

My code where I get the props destructured weather = 'Drizzle' would be the prop, for example)例如,我获得道具 destructured weather = 'Drizzle'代码将是道具)

import React from "react";
import styled from "styled-components";

import Drizzle from "../img/Drizzle.jpg";
import Cloudy from "../img/Cloudy.jpg";

const CardItems = styled.div`
  background-image: url(${Drizzle});


export default function Card({ max, min, name, img, onClose, weather }) {
  let icon = `http://openweathermap.org/img/wn/${img}@2x.png`;

  return (
    <CardItems>
      <TitleTwo>{name}</TitleTwo>
      <Image src={icon} alt="" />
      <TempsContainer>
        <TempText>
          <p>Min.</p>
          <p>{min}</p>
        </TempText>
        <TempText>
          <p>Max.</p>
          <p>{max}</p>
        </TempText>
      </TempsContainer>
    </CardItems>
  );
}

Replace:代替:

`background-image: url(${weather => (weather === 'Drizzle) ? Drizzle : Cloudy})`

by:经过:

`background-image: ${(props) => props.current === 'Drizzle' ? `url(${Drizzle})` : `url(${Cloudy})`};`

App.js应用程序.js

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

import Card from './Card';

export default function App() {
  return <Card weather="Drizzle" />;
}

Card.js Card.js

import React from 'react';
import styled from 'styled-components';

import Drizzle from './img/Drizzle.jpg';
import Cloudy from './img/Cloudy.jpg';

export default function Card({ weather }) {   
  return (
   <CardItems current={weather} />
  );
}

const CardItems = styled.div`
  height: 100vh;
  width: 100%;
  background-image: ${(props) =>
    props.current === 'Drizzle' ? `url(${Drizzle})` : `url(${Cloudy})`};
`;

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

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