簡體   English   中英

將函數組件轉換為類組件

[英]convert function components to class components

我在這里有這個類組件

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 中嘗試了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時,您可能需要盡快返回
  • 您還可以將組件包裹在錯誤邊界組件中
  • 如果你想使用已經在生產中使用的完整功能組件,請隨意使用我寫了一個名為atpro-howler的包,它是通過react-aptor與 react 集成的 howler

猛禽咆哮者

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM