首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React-player如何通过自动播放来处理播放暂停状态

React-player如何通过自动播放来处理播放暂停状态
EN

Stack Overflow用户
提问于 2021-10-03 13:22:41
回答 2查看 1.5K关注 0票数 1

我有一个自动播放策略的问题,它完全扰乱了我的自定义布局。

在组件中,有一个默认设置为true的"play“状态来触发自动播放,但在刷新页面后,即使"play”状态设置为true,自动播放也不起作用。现在的问题是,当用户单击play按钮时,状态不会改变,因为它已经是true,解决方案是将其设置为false并再次设置为true,但在此解决方案中,用户必须在图标上单击两次。

有人能帮我吗?也许react-player已经有了触发播放的状态或方法,而我不需要" play“状态来处理播放暂停。

下面是一个简单的示例,说明它是如何工作的

代码语言:javascript
复制
export default function Untitled() {
    const playerRef = useRef(null);
    const [playing, setPlaying] = useState(true)
    return (
    <div>
        <ReactPlayer
            style={{display:"none"}}
            controls={false}
            playing={playing}
            wrapper={"audio"}
            progressInterval={200}
            config={{
              file: {
                attributes: {preload: "auto"},
                forceAudio:true,
              },
            }}
        />
        <IconButton size="small">
            {playerRef && playerRef.current.player.isPlaying ? (
              <PauseIcon onClick={() => setPlaying(false)}/>
            ) : (
              <PlayArrowIcon onClick={() => setPlaying(true)}/>
            )}
        </IconButton>
    </div>
    )
}

EN

回答 2

Stack Overflow用户

发布于 2021-10-03 14:15:38

这是因为您没有将"ref“传递/赋值给"ReactPlayer”组件。

在这种情况下,ref不是必需的。

代码语言:javascript
复制
export default function Untitled() {
    const [playing, setPlaying] = useState(true)
    return (
    <div>
        <ReactPlayer
            style={{display:"none"}}
            controls={false}
            playing={playing}
            wrapper={"audio"}
            progressInterval={200}
            config={{
              file: {
                attributes: {preload: "auto"},
                forceAudio:true,
              },
            }}
        />
        <IconButton size="small">
            {playing? (
              <PauseIcon onClick={() => setPlaying(false)}/>
            ) : (
              <PlayArrowIcon onClick={() => setPlaying(true)}/>
            )}
        </IconButton>
    </div>
    )
}
票数 0
EN

Stack Overflow用户

发布于 2021-10-03 21:20:14

解决方案

代码语言:javascript
复制
var promise = document.querySelector('video').play();

if (promise !== undefined) {
  promise.then(_ => {
    // Autoplay started!
  }).catch(error => {
    // Autoplay was prevented.
    // Show a "Play" button so that user can start playback.
  });
}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69425243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档