gpt4 book ai didi

javascript - 使用 HTML5 在 React 中构建简单的音频播放器时遇到问题

转载 作者:行者123 更新时间:2023-11-28 03:00:26 26 4
gpt4 key购买 nike

我最近开始学习 React,我正在尝试构建一个简单的音频播放器。我目前正在使用此示例作为引用,但它内置在一个文件中

https://github.com/CezarLuiz0/react-cl-audio-player

我尝试制作的是一种“React”方式,其中 UI 具有可重用的组件,但我无法将我的代码分离为有意义且有效的组件。例如,如果我尝试将一些渲染代码从父组件 (AudioPlayer) 移动到 (PlayButton) 中,则在父组件的安装上创建的音频方法突然变得子组件无法访问。

这是我的代码库。

https://github.com/vincentchin/reactmusicplayer

它现在可以工作了,但我想改进它。另外,如果有人能指出其中的巨大缺陷,那就太好了,因为我确定我已经违反了一些 React 编码规则或标准。

最佳答案

您可以通过将方法作为 prop 传递,然后在子组件内部调用它,从子组件访问父组件的方法。

例如(在子组件的render方法中):

<button onClick={this.props.methodFromTheParent}>Click me</button>

您还可以将参数传递给这些方法:

<button onClick={this.props.methodFromTheParent.bind(null, 'Hello')}>Click me</button>

记得传入null而不是 this作为将值绑定(bind)到属于父组件的方法时的第一个参数。

我也浏览了你的 repo 协议(protocol)。通过将不同的元素放入它们自己的组件中,您可以大大清理 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> )。

关于javascript - 使用 HTML5 在 React 中构建简单的音频播放器时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com