我最近开始学习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>
)中添加该属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句