如何在React.js中实现媒体查询以获得完整的背景图像?

时间:2018-08-13 05:17:10

标签: css reactjs media-queries

有人可以帮助我解决React / CSS /媒体查询问题吗?我正在尝试创建一个具有完整宽度和高度背景图像的首页。当我使用const = bg {..}在react文件中创建样式时,它适用于桌面宽度。但是当使用css文件时,我无法使其正常工作。媒体查询应切换图片网址以缩小屏幕尺寸。

import React from "react";
import { connectContext } from "react-connect-context";
import { Context } from "../context";
import Menu from "./Menu";
import Footer from "./Footer";
import { Header } from "semantic-ui-react";
import "./Frontpage.css";

const textStyle = {
  width: 220,
  height: 50,
  position: "absolute",
  top: 0,
  bottom: 0,
  left: 0,
  right: 0,
  margin: "auto"
};

class Frontpage extends React.PureComponent {
  render() {
    return (
      <React.Fragment>
        <Menu {...this.props} />
        <div className="bg">
          <Header
            as="h1"
            content="Evolve App"
            textAlign="center"
            inverted
            style={textStyle}
          />
        </div>
        <Footer />
      </React.Fragment>
    );
  }
}

export default connectContext(Context)(Frontpage);

和Frontpage.css文件如下:

bg {
  background-image: url(../img/Frontpage_desktop.jpeg);
  background-position: "center";
  background-repeat: "no-repeat";
  opacity: 0.6;
  height: "100vh";
}

@media only screen and (min-width: 768px) and (max-width: 991px) {
  bg {
    background-image: url(../img/Frontpage_tablet.jpg);
    background-position: "center";
    background-repeat: "no-repeat";
    opacity: 0.6;
    height: "100vh";
  }
}

@media only screen and (max-width: 767px) {
  bg {
    background-image: url(../img/Frontpage_mobile.jpg);
    background-position: "center";
    background-repeat: "no-repeat";
    opacity: 0.6;
    height: "100vh";
  }
}

1 个答案:

答案 0 :(得分:2)

您可以尝试通过React组件设置宽度。尝试此操作,使用componentDidMount()生命周期方法,并使用window.innerWidth函数设置图像的宽度,然后直接在组件中使用图像。

class Frontpage extends React.PureComponent {
  state = {
  image_width: null,
  image_height: null
  }

  componentDidMount() {
    this.setImageSize()
  }

  setImageSize = () => {
   if(window.innerWidth < 768) {
       this.setState({image_width: 400, image_height: 400})
     } else {
       this.setState({image_width: 500, image_height: 500})
     }  
   }

  render() {
    return (
      <React.Fragment>
        <Menu {...this.props} />
        <img src="../img/Frontpage_tablet.jpg" width={this.state.image_width} height={this.state.image_height} /> 
          <Header
            as="h1"
            content="Evolve App"
            textAlign="center"
            inverted
            style={textStyle}
          />
        </div>
        <Footer />
      </React.Fragment>
    );
  }
}

您可能需要在图片上使用三元表达式

{ this.state.image_width
 ? <img ... /> 
 : null 
} 

我有一个类似的问题,这应该适合您。