如何将功能组件转换为类组件?

时间:2020-04-22 07:19:24

标签: reactjs react-native redux react-redux

这是我要使用的功能组件示例。

https://github.com/react-native-kit/react-native-track-player/blob/dev/example/react/screens/PlaylistScreen.js

如何将其转换为类组件?

import React, { useEffect } from "react";
import { StyleSheet, Text, View } from "react-native";
import TrackPlayer from "react-native-track-player";

import Player from "../components/Player";
import playlistData from "../data/playlist.json";
import localTrack from "../resources/pure.m4a";

export default function LandingScreen() {
  const playbackState = TrackPlayer.usePlaybackState();

  useEffect(() => {
    TrackPlayer.setupPlayer();
    TrackPlayer.updateOptions({
      stopWithApp: false,
      capabilities: [
        TrackPlayer.CAPABILITY_PLAY,
        TrackPlayer.CAPABILITY_PAUSE,
        TrackPlayer.CAPABILITY_SKIP_TO_NEXT,
        TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS,
        TrackPlayer.CAPABILITY_STOP
      ],
      compactCapabilities: [
        TrackPlayer.CAPABILITY_PLAY,
        TrackPlayer.CAPABILITY_PAUSE
      ]
    });
  }, []);

  async function togglePlayback() {
    const currentTrack = await TrackPlayer.getCurrentTrack();
    if (currentTrack == null) {
      await TrackPlayer.reset();
      await TrackPlayer.add(playlistData);
      await TrackPlayer.add({
        id: "local-track",
        url: localTrack,
        title: "Pure (Demo)",
        artist: "David Chavez",
        artwork: "https://picsum.photos/200"
      });
      await TrackPlayer.play();
    } else {
      if (playbackState === TrackPlayer.STATE_PAUSED) {
        await TrackPlayer.play();
      } else {
        await TrackPlayer.pause();
      }
    }
  }

  return (
    <View style={styles.container}>
      <Text style={styles.description}>
        We'll be inserting a playlist into the library loaded from
        `playlist.json`. We'll also be using the `ProgressComponent` which
        allows us to track playback time.
      </Text>
      <Player
        onNext={skipToNext}
        style={styles.player}
        onPrevious={skipToPrevious}
        onTogglePlayback={togglePlayback}
      />
      <Text style={styles.state}>{getStateName(playbackState)}</Text>
    </View>
  );
}

LandingScreen.navigationOptions = {
  title: "Playlist Example"
};

function getStateName(state) {
  switch (state) {
    case TrackPlayer.STATE_NONE:
      return "None";
    case TrackPlayer.STATE_PLAYING:
      return "Playing";
    case TrackPlayer.STATE_PAUSED:
      return "Paused";
    case TrackPlayer.STATE_STOPPED:
      return "Stopped";
    case TrackPlayer.STATE_BUFFERING:
      return "Buffering";
  }
}

async function skipToNext() {
  try {
    await TrackPlayer.skipToNext();
  } catch (_) {}
}

async function skipToPrevious() {
  try {
    await TrackPlayer.skipToPrevious();
  } catch (_) {}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  description: {
    width: "80%",
    marginTop: 20,
    textAlign: "center"
  },
  player: {
    marginTop: 40
  },
  state: {
    marginTop: 20
  }
});

我尝试如下。但这给了我错误。

import React, { Component, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, Image, AsyncStorage } from 'react-native';
import Icon from 'react-native-vector-icons/AntDesign';
import Player from './Player'
import TrackPlayer from 'react-native-track-player';

// const playbackState = TrackPlayer.usePlaybackState();  // I don't know how to manage this.

export default class MusicPlayer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      full: true,
      clicked: '',
    };
  }

  componentWillMount() {
    TrackPlayer.setupPlayer();
    TrackPlayer.updateOptions({
      stopWithApp: false,
      capabilities: [
        TrackPlayer.CAPABILITY_PLAY,
        TrackPlayer.CAPABILITY_PAUSE,
        TrackPlayer.CAPABILITY_SKIP_TO_NEXT,
        TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS,
        TrackPlayer.CAPABILITY_STOP
      ],
      compactCapabilities: [
        TrackPlayer.CAPABILITY_PLAY,
        TrackPlayer.CAPABILITY_PAUSE
      ]
    });
  }

  async togglePlayback() {
    const currentTrack = await TrackPlayer.getCurrentTrack();
    if (currentTrack == null) {
      await TrackPlayer.reset();
      await TrackPlayer.add(playlistData);
      await TrackPlayer.add({
        id: "local-track",
        url: 'http://192.168.22.27:8000/' + this.props.navigation.getParam('clickedSource'),
        title: "Pure (Demo)",
        artist: "David Chavez",
        artwork: "https://picsum.photos/200"
      });
      await TrackPlayer.play();
    } else {
      if (playbackState === TrackPlayer.STATE_PAUSED) {
        await TrackPlayer.play();
      } else {
        await TrackPlayer.pause();
      }
    }
  }

  async skipToNext() {
    try {
      await TrackPlayer.skipToNext();
    } catch (_) { }
  }

  async skipToPrevious() {
    try {
      await TrackPlayer.skipToPrevious();
    } catch (_) { }
  }

  render() {
    return (
      <View style={styles.container} >
        <Player
          onNext={()=>this.skipToNext()}
          style={styles.player}
          onPrevious={()=>this.skipToPrevious()}
          onTogglePlayback={()=>this.togglePlayback()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  player: {
    marginTop: 40
  },
});

如何将其转换为类组件?

1 个答案:

答案 0 :(得分:2)

usePlaybackState是一个反应钩子,但似乎存在一个getState函数,该函数返回一个Promise。您不希望存储该状态对象,因为它可能很快就会过时,因此根本不需要使用this.playbackState。每次需要访问当前播放器状态时,您只需等待它。

const playbackState = await TrackPlayer.getState(); // <-- get player state
if (playbackState === TrackPlayer.STATE_PAUSED) {
  await TrackPlayer.play();
} else {
  await TrackPlayer.pause();
}

完整代码

import React, { Component, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, Image, AsyncStorage } from 'react-native';
import Icon from 'react-native-vector-icons/AntDesign';
import Player from './Player'
import TrackPlayer from 'react-native-track-player';

export default class MusicPlayer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      full: true,
      clicked: '',
    };
  }

  componentWillMount() {
    TrackPlayer.setupPlayer();
    TrackPlayer.updateOptions({
      stopWithApp: false,
      capabilities: [
        TrackPlayer.CAPABILITY_PLAY,
        TrackPlayer.CAPABILITY_PAUSE,
        TrackPlayer.CAPABILITY_SKIP_TO_NEXT,
        TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS,
        TrackPlayer.CAPABILITY_STOP
      ],
      compactCapabilities: [
        TrackPlayer.CAPABILITY_PLAY,
        TrackPlayer.CAPABILITY_PAUSE
      ]
    });
  }

  async togglePlayback() {
    const currentTrack = await TrackPlayer.getCurrentTrack();
    if (currentTrack == null) {
      await TrackPlayer.reset();
      await TrackPlayer.add(playlistData);
      await TrackPlayer.add({
        id: "local-track",
        url: 'http://192.168.22.27:8000/' + this.props.navigation.getParam('clickedSource'),
        title: "Pure (Demo)",
        artist: "David Chavez",
        artwork: "https://picsum.photos/200"
      });
      await TrackPlayer.play();
    } else {
      const playbackState = await TrackPlayer.getState(); // <-- get player state
      if (playbackState === TrackPlayer.STATE_PAUSED) {
        await TrackPlayer.play();
      } else {
        await TrackPlayer.pause();
      }
    }
  }

  async skipToNext() {
    try {
      await TrackPlayer.skipToNext();
    } catch (_) { }
  }

  async skipToPrevious() {
    try {
      await TrackPlayer.skipToPrevious();
    } catch (_) { }
  }

  render() {
    return (
      <View style={styles.container} >
        <Player
          onNext={()=>this.skipToNext()}
          style={styles.player}
          onPrevious={()=>this.skipToPrevious()}
          onTogglePlayback={()=>this.togglePlayback()}
        />
      </View>
    );
  }
}