为什么 React 中忽略了 video 标签上的 `muted` 属性?

Mhm*_*z_A 4 html javascript reactjs

好吧,尽管听起来违反直觉,但muted标签在某种程度上被忽略了;查看下面的代码片段,第一个是用 react 渲染的,第二个是普通的 html;与你的开发工具检查他们,你看到的反应上具有muted的属性; 我已经试过了muted={true}muted="true"但非工作。

function VideoPreview() {
  return (
    <div className="videopreview-container">
      React tag:
      <video
        className="videopreview-container_video"
        width="320"
        height="240"
        controls
        autoPlay
        muted
      >
        <source src="https://raw.githubusercontent.com/rpsthecoder/h/gh-pages/OSRO-animation.mp4" type="video/mp4" />
        Your browser does not support the video tag.
      </video>
    </div>
  );
}

ReactDOM.render(<VideoPreview />, root)
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


<div id="root"></div>


<hr/>
Regular html:
<video
  width="320"
  height="240"
  controls
  autoplay
  muted
>
  <source src="https://raw.githubusercontent.com/rpsthecoder/h/gh-pages/OSRO-animation.mp4" type="video/mp4" />
  Your browser does not support the video tag.
</video>
Run Code Online (Sandbox Code Playgroud)

小智 7

这实际上是一个自 2016 年以来就存在的已知问题。视频将被正确静音,但不会在 DOM 中设置该属性。您可以在 GitHub 问题中找到多种解决方法,尽管其中任何一种都可能有利有弊。


Cod*_*ife 5

正如 @FluidSense 所提到的,它永远是一个开放的错误。

我可以这样实现:

import React, { useRef, useEffect } from "react";

export default function Video({ src, isMuted }) {
    const refVideo = useRef(null);

    useEffect(() => {
        if (!refVideo.current) {
            return;
        }

        if (isMuted) {
            //open bug since 2017 that you cannot set muted in video element https://github.com/facebook/react/issues/10389
            refVideo.current.defaultMuted = true;
            refVideo.current.muted = true;
        }

        refVideo.current.srcObject = src;
    }, [src]);

    return (
            <video
                ref={refVideo}
                autoPlay
                playsInline //FIX iOS black screen
            />
    );
}
Run Code Online (Sandbox Code Playgroud)