将函数组件转换为 class 个组件

convert function components to class components

我这里有这个 class 组件

class App extends React.Component {
  getHowler() {
    this.player.howler;
  }

  getDuration() {
    this.player.duration();
  }

  getSeek() {
    this.player.seek();
  }

  setSeek() {
    this.player.seek(0.5);
  }
  // This sound file may not work due to cross-origin setting
  render() {
    return (
      <ReactHowler
        src="http://goldfirestudios.com/proj/howlerjs/sound.ogg"
        playing={true}
        ref={(ref) => (this.player = ref)}
      />
    );
  }
}

我想把它转换成函数组件。我想使用 React 中的 React howler seek function in function components. How can I do that? I tried useRef,它会抛出一个错误。

该功能应如下所示: 每次我换曲目它应该从头开始播放

const App = () => {
  const player = useRef(null)

  const getHowler = () => {
    player.current.howler;
  }

  const getDuration = () => {
    player.current.duration();
  }

  const getSeek () => {
    player.current.seek();
  }

  const setSeek = () => {
    player.current.seek(0.5);
  }

  render() {
    return (
      <ReactHowler
        src="http://goldfirestudios.com/proj/howlerjs/sound.ogg"
        playing={true}
        ref={player}
      />
    );
  }
}
  • 您可能需要在 player.current === null
  • 时尽快 return
  • 也可以将组件包裹在Error boundary组件中
  • 如果你想使用已经在生产中使用的完整功能组件,请随意使用我写的一个名为 atpro-howler which is howler integrated with react via react-aptor
  • 的包