首页 > 解决方案 > 我似乎无法显示背景图像。背景图像显示一瞬间,但随后崩溃“无法执行 CreateElement”

问题描述

我尝试根据时间更改背景图像,但使用带有 document.body.style.backgroundImage 的函数 if-else

我查看了控制台日志以进一步了解它。图片显示并且背景图像在 html 正文样式中正确显示 = 但它一直给我一个错误,说无法在“文档”上执行“createElement”

import React from 'react';

import lo from "/Users/justinandhang/Desktop/menu/menu2/src/photo/lo.png"


function ClockImage() {
    const date = new Date()
    const hours = date.getHours()
    let timeOfDay
    if (hours < 12) {
        return document.body.style.backgroundImage = 'url("'+lo+'")'

    }
    else if (hours >= 12 && hours < 17) {
        return document.body.style.backgroundImage = `url("${lo}")`
    }else {
        return document.body.style.backgroundImage = 'url("/Users/justinandhang/Desktop/menu/menu2/src/photo/lo.png")'     
    }


}

export default ClockImage()

索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import MenuContainer from "./MenuContainer"
import city from "/Users/justinandhang/Desktop/menu/menu2/src/photo/turntable_vignette.gif"
import lo from "/Users/justinandhang/Desktop/menu/menu2/src/photo/lo.png"
import ClockImage from "/Users/justinandhang/Desktop/menu/menu2/src/ClockImage.js"



ReactDOM.render(
    <div>
        <ClockImage />
        <MenuContainer />
    </div>
    , document.getElementById('container'));

该错误表示无效字符错误:无法在“文档”上执行“CreateElement”。

我尝试了 3 种不同的方式来不同地链接 url,但它返回相同的错误!

标签: htmlcssreactjs

解决方案


您收到该错误是因为您正在导出ClockImage()首先调用该函数然后导出返回值,并且在index.jsReact 中无法呈现ClockImage,因为它不是一个组件。

您需要改为导出ClockImage

export default ClockImage;

附注:仅仅为了改变样式而创建/渲染组件并不是一个好主意。


推荐阅读