【问题标题】:React dynamic background image using useWindowWidth使用 useWindowWidth 反应动态背景图像
【发布时间】:2021-01-11 05:21:51
【问题描述】:

我在 react 的动态背景图像上遇到了一些问题。我可以看到 mobileImage“image-2.jpg”,但 desktopImage 没有加载。我已经尝试根据文档应用一些代码,但我的代码出现错误,请查看并帮助我。

下面是我的代码:

ProjectItem.js

import React from 'react';
import './ProjectItem.scss';
import useWindowWidth from '../../Hooks/useWindowWidth.js';

import desktopImage from '../../Assets/Images/Projects/Desktop/Image-1.jpg';
import mobileImage from '../../Assets/Images/Projects/Mobile/Image-2.jpg'

const ProjectItem = ({ desktopImage, title, viewProject }) => {

const imageUrl = useWindowWidth() >= 650 ? desktopImage : mobileImage;
const { windowWidth } = useWindowWidth();

return(
<div className="projectItem" style={{ backgroundImage: `url(${ imageUrl })`, height: '500px'}}>
       {windowWidth >= 650 &&( 
           <>
           <div className="title">{title}</div> 
           <div className="viewProject">{viewProject}</div>
           </>
       )}  
   </div>
);
}; 

export default ProjectItem

下面是我的代码:

ProjectItem.scss

.projectItem{
width: 600px;
height: 450px;
display: block;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}

以下是错误:

控制台

./src/Components/Home/ProjectItem.js
Line 5:8:  'desktopImage' is defined but never used  no-unused-vars
printWarnings   @   webpackHotDevClient.js:138
handleWarnings  @   webpackHotDevClient.js:143
push../node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage @   webpackHotDevClient.js:210

【问题讨论】:

    标签: reactjs react-hooks components


    【解决方案1】:

    通过查看您的代码,我认为问题在于您的ProjectItem 中的desktopImage 指的是从ProjectItem 的道具解构的desktopImage,而不是在您的组件上方导入的desktopImage 变量。

    所以解决方案就是不要从ProjectItem的道具中解构desktopImage

    const ProjectItem = ({ title, viewProject }) => {
      // etc...
    }
    

    这也解释了desktopImage 已定义但从未使用过的警告。

    【讨论】:

    • 嗨,Bas,我已经从 Projec tItem 的道具中删除了 destructured desktopImage,正如您所提到的,它有效,谢谢!
    猜你喜欢
    • 2023-03-28
    • 2023-02-19
    • 2018-05-04
    • 2021-01-25
    • 1970-01-01
    • 2019-08-25
    • 2021-08-03
    • 2020-06-28
    • 2016-05-06
    相关资源
    最近更新 更多