【问题标题】:React: Play, pause onclick fuctionalityReact:播放,暂停点击功能
【发布时间】:2020-04-17 06:37:46
【问题描述】:

我正在尝试在单击按钮时实现播放/暂停。虽然图标完美改变,但我的实际功能无法正常工作。我的代码如下。

点击触发的功能

onPlayHandler = () => {
        let aud = new Audio(this.props.data[this.state.index].audio);
        aud.play();
        this.setState({
            isPlaying: true
        });
    };

    onPauseHandler = () => {
        let aud = new Audio(this.props.data[this.state.index].audio);
        aud.pause()
        //aud.setAttribute("ref", `${this.myRef}`);
        this.setState({
            isPlaying: false
        });
        //this.refs.audio.pause(); 
        //x.pause(); 
        //console.log(aud)
    };

被点击的按钮

<Button playAudio={ this.state.isPlaying ? this.onPauseHandler : this.onPlayHandler } isPlaying={ this.state.isPlaying } />

按钮组件

export default function IconLabelButtons(props) {
    const classes = useStyles();

    return (
        <>
            <Button
                variant="contained"
                color="primary"
                size="large"
                className={ classes.button }
                startIcon={ props.isPlaying ? <PauseIcon /> : <PlayArrowIcon /> }
                onClick={ props.playAudio }
            >
                { props.isPlaying ? 'Pause' : 'Play' }
            </Button>
        </>
    );

更新的问题 完整代码

import React, { Component } from 'react';
import Card from './Card';
import Button from './Button';
import correct from '../../data/media/correct.wav';
import denied from '../../data/media/denied.mp3';
var _ = require('lodash');


class AudioContainer extends Component {
    constructor (props) {
        super(props);
        this.state = {
            images: [],
            index: 0,
            checkedItems: new Map(),
            correct: false,
            isPlaying: false
        };
        this.audio = React.createRef();
    }

    componentDidMount() {

        const arrImages = this.props.data.map((item) => {
            let arr = [];
            arr.push(item.picture);
            return arr;
        });

        //console.log(arrImages)
        this.setState({
            images: _.shuffle(arrImages.flat(Infinity))
        });
    }

    showImages = () => {
        this.state.images && this.state.images.map((image) => (
            <div>
                <figure class="image is-128x128">
                    <img src={ image.src } alt="" />
                </figure>
                <span>{ image.name }</span>
            </div>
        ));
    };

    handleChange = (e) => {
        const item = e.target.name;
        const isChecked = e.target.checked;
        this.setState(prevState => ({ checkedItems: prevState.checkedItems.set(item, isChecked) }));
    };

    onCheckHandler = (e) => {
        e.preventDefault();
        /* function checkTrue(item) {
            return item.value === true;
        }
        const filteredItems = this.state.checkedItems.filter(checkTrue) */
        //console.log(this.state.checkedItems.value())
        let arr = [];
        // eslint-disable-next-line no-unused-vars
        for (let [key, value] of this.state.checkedItems) {
            let obj = {
                value: key,
                bool: value
            };
            arr.push(obj);
        }

        //console.log(arr);
        let filteredArr = arr.filter((el) => {
            return el.bool === true;
        });
        //console.log(filteredArr);
        let arrWithAnswers = [];
        filteredArr.map((el) => {
            return arrWithAnswers.push(el.value);
        });
        //console.log(arrWithAnswers);
        //console.log(this.props.data[this.state.index].answers.sort());
        if (_.isEqual(arrWithAnswers.sort(), this.props.data[this.state.index].answers.sort())) {
            let sound = new Audio(correct);
            sound.play();
            this.setState({
                index: this.state.index + 1, checkedItems: new Map()
            });
            //console.log("true");
        } else {
            let sound = new Audio(denied);
            sound.play();
        }
    };

    update() {
        const arrImages = this.props.data.map((item) => {
            let arr = [];
            arr.push(item.picture);
            return arr;
        });

        //console.log(arrImages)
        this.setState({
            images: _.shuffle(arrImages.flat(Infinity))
        });
    }

    onPlayHandler = () => {
        let aud = new Audio(this.props.data[this.state.index].audio);
        aud.play();
        this.setState({
            isPlaying: true
        });
    };

    onPauseHandler = () => {
        let aud = new Audio(this.props.data[this.state.index].audio);
        aud.pause()
        //aud.setAttribute("ref", `${this.myRef}`);
        this.setState({
            isPlaying: false
        });
        //this.refs.audio.pause(); 
        //x.pause(); 
        //console.log(aud)
    };

    render() {
        //console.log(this.props.data)
        //console.log(this.state.images)
        //console.log(this.state.checkedItems.size);
        return (
            <div>
                <Button playAudio={ this.state.isPlaying ? this.onPauseHandler : this.onPlayHandler } isPlaying={ this.state.isPlaying } />
                <div className="columns is-vcentered is-multiline">
                    { this.state.images && this.state.images.map((image, index) => (
                        <div className="column is-3" key={index}>
                            <Card image={ image.src } clickHandler={ this.handleChange } name={ image.name } />
                        </div>
                    )) }
                </div>

                <button className="button is-info" disabled={ this.state.checkedItems.size <= 0 } onClick={ this.onCheckHandler }>Check</button>
            </div>
        );
    }
}

export default AudioContainer;

感谢您的帮助,谢谢。

【问题讨论】:

  • 展示更多代码,您的音频元素/组件是如何创建的?
  • 好的,我会更新问题
  • 播放/暂停应该总是创建一个新的音频对象吗?请分享您的组件代码的完整示例。
  • 建议:不要使用 2 个不同的回调向您的 Button 发送自定义 playAudio,而只需使用一个回调 &lt;Button playAudio={playAudio} &gt; 然后在您的 playAudio 函数中,检查 state.isPlaying 的值来决定怎么办
  • 您在每次操作时都初始化一个新的Audio 看起来很可疑

标签: reactjs audio


【解决方案1】:

我能够以我想要的方式得到它,但我不确定这是否是一个好习惯。所以我做的是以下。

let audio = new Audio()

class AudioContainer extends Component {
    constructor (props) {
        super(props);
        this.state = {
            images: [],
            index: 0,
            checkedItems: new Map(),
            correct: false,
            isPlaying: false,
            error: false
        };

    }


onPlayHandler = () => {
        audio.src = this.props.data[this.state.index].audio
        audio.play();
        this.setState({
            isPlaying: true
        });
    };

    onPauseHandler = () => {
        audio.src = this.props.data[this.state.index].audio
        //let aud = new Audio(this.props.data[this.state.index].audio);
        audio.pause();
        //aud.setAttribute("ref", `${this.myRef}`);
        this.setState({
            isPlaying: false
        });
        //this.refs.audio.pause(); 
        //x.pause(); 
        //console.log(aud)
    };

我非常怀疑在最顶部声明​​可变音频。所以如果我错了,请纠正我。

【讨论】:

    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    相关资源
    最近更新 更多