css - 反应在更新时更改 CSS 背景
问题描述
尝试在此 React 应用程序中切换 CSS 背景图像。我已经导入了图片。然后我为导入的图像设置一个变量“图像”,因为点击时迭代增加/减少。
问题是身体背景图像似乎没有更新。我认为背景图像会在 componentDidUpdate 中刷新,因为迭代按钮切换 setState 应该强制渲染。
import Background1 from "../images/bg/1.png";
import Background2 from "../images/bg/3.png";
import Background3 from "../images/bg/4.png";
class UserPreferences extends Component {
constructor(props) {
super(props);
this.state = {
backgroundNumber: 1
};
}
buttonNumberCalcPlus = () => {
this.setState({ backgroundNumber: ++this.state.backgroundNumber });
};
buttonNumberCalcMinus = () => {
this.setState({ backgroundNumber: --this.state.backgroundNumber });
};
componentDidUpdate() {
var currentBackground = "Background" + this.state.backgroundNumber;
console.log(currentBackground);
var image;
if (this.state.backgroundNumber == 1) {
image = Background1;
} else if (this.state.backgroundNumber == 2) {
image = Background2;
} else {
image = Background3;
}
var mainBg = {
backgroundImage: "url( " + { image } + ")"
};
console.log(mainBg);
document.body.style = { mainBg };
}
render() {
return (
<div>
<MainMenuToolbar />
<h2 className="texttimezonepref">Change background image.</h2>
<button
id="next"
onClick={this.buttonNumberCalcPlus}
className="addbutton"
>
NEXT
</button>
<button
id="prev"
onClick={this.buttonNumberCalcMinus}
className="subtractbutton"
>
PREV
</button>
</div>
);
}
}
这是在componentDidUpdate中更改背景的正确方法吗:
var mainBg = {
backgroundImage: "url( " + { image } + ")"
};
document.body.style = { mainBg };
解决方案
The document.body.style is not JSX, and does not accept the document.body.style = {{ backgroundImage: "url( " + { image } + ")"}}
as you're expecting.
Instead, you want to just apply your style change to the target directly, such as:
document.body.style.backgroundImage = url(image)
推荐阅读
- swift - 使用 @ObservedObject 包装的核心数据对象会导致 NavigationLink 目标在该对象被删除时重新呈现
- python - 如何从特定键中获取值
- javascript - 如何使用 vuejs 将数据“推送()”到 firebase 中的现有数组?
- python - 使用生成的用户名填充 Django 用户名字段
- visual-studio-code - 如何在 VSCode 中禁用 TS6133 “XXXXX is declared but its value is never used”警告?
- amazon-web-services - 服务器列表的 Cloudwatch 警报
- algorithm - 交错两个未排序的数组以获得词典最大的结果
- posix - POSIX 是否要求 `getconf V7_ENV` 有效?
- python - Rosalind 共识和配置文件问题代码不起作用
- excel - 在excel中提取特定字符之间的字符串并用逗号分隔它们