首页 > 解决方案 > React Native Video,如何动态更改源?

问题描述

我正在尝试在 React-Native 中播放视频。问题是我可以使用相对路径(“../videos/test.mp4”)来实现这一点,但是当我使用像(this.state.path)这样的变量时,我会收到以下错误下方留言。有人可以帮我吗?

错误 点击这里查看错误

主班

export default class level1 extends React.Component {

    constructor() {
        super();
        this.state = {
            path: script[0].path,
            repeat: script[0].repeat,
            finished: false,
            scriptIterator: 0
        }
        this.videoFinished = this.videoFinished.bind(this);
        
    }


    videoFinished() {
        var i = this.state.scriptIterator + 1;
        if (this.state.repeat) {
            // clicklistener
            console.warn("clicklistener");
        }
        
        this.setState({
            finished: false,
            scriptIterator: i,
            path: script[i].path,
            repeat: script[i].repeat
        })
    }


    render() {
        return (
            <View>
                <VideoClass
                    path={this.state.path}
                    repeat={this.state.repeat}
                    onEnd={this.videoFinished}
                />
            </View>
        )
    }
}

const script =
    [
        { path: "../videos/APB.mp4", repeat: false },
        { path: "../videos/test.mp4", repeat: true }
    ]

视频类

export default class VideoClass extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            path: props.path,
            repeat: props.repeat
        }
    }

    render() {
        return (
            <Video
                source={require(this.state.path)} 
                style={styles.backgroundVideo}
                muted={true}
                repeat={this.state.repeat}
                resizeMode={"cover"}
                rate={1.0}
                ignoreSilentSwitch={"obey"}
                onEnd={() => this.props.onEnd()}
            />
        );
    }
}

标签: androidiosreactjsreact-nativevisual-studio-code

解决方案


首先,在您的 VideoClass 组件中,您应该传递this.props.pathsource属性和this.props.repeat属性repeat,因为您的状态是在您的 level1 组件中控制的

<Video
     source={this.props.path} 
     style={styles.backgroundVideo}
     muted={true}
     repeat={this.props.repeat}
     resizeMode={"cover"}
     rate={1.0}
     ignoreSilentSwitch={"obey"}
     onEnd={() => this.props.onEnd()}
    />

然后在您的 level1 组件中,您应该将scriptconst 更改为:

const script =
    [
        { path: require("../videos/APB.mp4"), repeat: false },
        { path: require("../videos/test.mp4"), repeat: true }
    ]

推荐阅读