html - 我似乎无法显示背景图像。背景图像显示一瞬间,但随后崩溃“无法执行 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,但它返回相同的错误!
解决方案
您收到该错误是因为您正在导出ClockImage()
首先调用该函数然后导出返回值,并且在index.js
React 中无法呈现ClockImage
,因为它不是一个组件。
您需要改为导出ClockImage
:
export default ClockImage;
附注:仅仅为了改变样式而创建/渲染组件并不是一个好主意。
推荐阅读
- python - 根据python中的值溶解多边形
- sql - SQL 两位小数
- google-cloud-platform - 重新启动后无法将远程桌面连接到 Windows 服务器
- python - 在多线程 Python 函数上使用 FastAPI 流式传输视频
- reactjs - 如何将参数传递给子组件
- javascript - Node.js vercel/pkg express 'return 0 error' 和 fastify 错误。错误:编译阶段文件或文件夹未包含在可执行文件中
- sql-server - sqlpackage.exe 发布失败,没有错误
- java - 从本地调用 Oracle 存储过程,本机查询工作正常,但部署到 QA 时,找不到存储过程
- django - 如何使用 django rest 框架后端设置服务器端事件
- java - Java:如何暂停线程执行,直到 JFrame 被释放