【问题标题】:Source tag didn't update the src attribute源标签没有更新 src 属性
【发布时间】: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


【解决方案1】:

改变这个

bgChange === backgroundDay
      ? setbgChange(backgroundNight)
      : setbgChange(backgroundDay);

setbgChange(
    bgChange === backgroundDay 
    ? backgroundNight 
    : backgroundDay
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2018-06-16
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多