[英]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.