[英]Having trouble building a simple audio player in React using HTML5
我最近開始學習React,並且正在嘗試構建一個簡單的音頻播放器。 我目前正在使用此示例作為參考,但它內置在一個文件中
https://github.com/CezarLuiz0/react-cl-audio-player
我嘗試制作的代碼是以“反應”方式完成的,其中UI具有可重用的組件,但是我很難將我的代碼分成有意義且有效的組件。 例如,如果我嘗試將某些渲染代碼從父組件(AudioPlayer)移到(PlayButton),則子組件在安裝父組件時創建的音頻方法突然變得不可訪問。
這是我的代碼庫。
https://github.com/vincentchin/reactmusicplayer
現在可以使用,但是我想改進它。 如果有人指出這一點上的巨大缺陷,那也是很棒的,因為我確信我違反了一些規則或標准來編寫React代碼。
通過將方法作為道具傳遞,然后在子組件內部調用它,可以從子組件訪問父組件的方法。
例如(在子組件的render方法中):
<button onClick={this.props.methodFromTheParent}>Click me</button>
您還可以將參數傳遞給以下方法:
<button onClick={this.props.methodFromTheParent.bind(null, 'Hello')}>Click me</button>
將值綁定到屬於父組件的方法時,請記住傳入null
而不是this
參數作為第一個參數。
我也瀏覽了您的回購。 您可以通過將不同的元素放入自己的組件中來清理AudioPlayer組件。
render方法可能看起來像這樣:
render() {
return (
<div>
<PlayButton onClick={this.togglePlay} playing={this.state.playing} />
{!this.state.hidePlayer ?
(<Player
playerState={this.state}
togglePlay={this.togglePlay}
setProgress={this.setProgress}
...
/>) : null}
</div>
);
}
然后在新創建的Player組件中:
render() {
var pState = this.props.playerState; // Just to make this more readable
return (
<div className="player">
<PlayButton onClick={this.props.togglePlay} playing={pState.playing} />
<Timeline
currentTimeDisplay={pState.currentTimeDisplay}
setProgress={this.props.setProgress}
progress={pState.progress}
...
/>
<VolumeContainer
onMouseLeave={this.props.noShow}
setVolume={this.setVolume}
toggleMute={this.toggleMute}
...
/>
</div>
);
}
您可以根據需要將布局分為多個嵌套組件,這很有意義。
請記住,實際上還要在子組件中添加onClick
屬性( <button onClick={this.props.onClick}>Play</button>
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.