将Component方法重构为单独的类

时间:2018-07-12 20:25:07

标签: reactjs class ecmascript-6

我在React中有一个组件,我想提取到它自己的实用程序类,因此我可以共享一些逻辑和功能,但是我不确定如何做到这一点。

为了论证,我的组件看起来像这样:

import React, { Component } from 'react';

const audio = new Audio();
const ctx = new (window.AudioContext || window.webkitAudioContext)();

const analyser = ctx.createAnalyser();
const source = ctx.createMediaElementSource(audio);

const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(analyser.frequencyBinCount);

class AudioEngine extends Component {
  audioEngine = new AudioEngine();

  componentDidMount() {
    this.configAudio();
  }

  configAudio = () => {
    audio.src = 'http://radio.domain.com:8000/listen.mp3';
    audio.controls = false;
    audio.autoplay = false;
    audio.crossOrigin = 'anonymous';
    analyser.fftSize = 2048;
    analyser.smoothingTimeConstant = 0.6;
    analyser.getByteFrequencyData(dataArray);

    source.connect(ctx.destination);
    source.connect(analyser);

    document.body.appendChild(audio);
  };

  render() {
    return <h3>Audio</h3>;
  }
}

export default AudioEngine;

不过,我想做的比该组件还要多,例如导出bufferLengthdataArray,以便可以在另一个组件中使用它们。

我还希望能够在另一个组件中调用audio.play()

可以这样做吗?

如何将其重构为类?

export default class AudioEngine {
  audio = new Audio();
  ctx = new (window.AudioContext || window.webkitAudioContext)();
  analyser = ctx.createAnalyser();
  source = ctx.createMediaElementSource(audio);

  bufferLength = analyser.frequencyBinCount;
  dataArray = new Uint8Array(analyser.frequencyBinCount);

  constructor() {
    this.streamUrl = streamUrl;
  }

  init = () => {
    audio.src = this.streamUrl;
    audio.controls = false;
    audio.autoplay = false;
    audio.crossOrigin = 'anonymous';
    analyser.fftSize = 2048;
    analyser.smoothingTimeConstant = 0.6;
    analyser.getByteFrequencyData(dataArray);

    source.connect(ctx.destination);
    source.connect(analyser);

    document.body.appendChild(audio);
  };

  play = () => this.audio.play();
}

这显然行不通,我很困惑如何进行

0 个答案:

没有答案
相关问题