【发布时间】:2022-01-09 05:46:00
【问题描述】:
我尝试使用 useState 更新视频背景,但似乎不起作用。
这是我的代码:
const [bgChange, setbgChange] = useState(backgroundDay);
const handleBackground = () => {
bgChange === backgroundDay
? setbgChange(backgroundNight)
: setbgChange(backgroundDay);
console.log(bgChange);
};
return (
<div className="container">
<div className="-z-50 absolute">
<video className="videoTag" autoPlay loop muted>
<source src={bgChange} type="video/mp4" />
</video>
</div>
<button onClick={handleBackground}>Change BG</button>
</div>
);
【问题讨论】:
-
bgChange的更新值将在下一次渲染中可用,因此将console.log移出handleBackground并检查结果。 -
背景没有任何改变@@
-
“什么都没有改变”是什么意思?当前发生了什么,您希望它做什么?
-
这看起来可能是存储在
backgroundNight和/或backgroundDay中的值有问题 -
我的意思是 src 属性没有更新,因此当我点击 Change BG 按钮时背景没有改变
标签: javascript html reactjs