简体   繁体   中英

convert function components to class components

I have this class component here

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)}
      />
    );
  }
}

I want this to convert into function components. I want to use react howler seek function in function components. How can I do that? I tried useRef from react and it throws me an error.

The functionality should work like this: every time I swap the tract it should play from the beginning

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}
      />
    );
  }
}
  • You might need to return asap when player.current === null
  • You can also wrap the component in the Error boundary component
  • If you want to use complete functional component already used in production, feel free to use the package I wrote a package named atpro-howler which is howler integrated with react via react-aptor

猛禽咆哮者

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM