TJK*_*TJK 3 javascript reactjs webpack array.prototype.map create-react-app
我大约两周时间开始学习 React 和我的第一个 SPA。我喜欢 react 并且能够解决我的许多问题,但是我在制作的这个 MusicPlayer 组件上遇到了两个问题。
一是当我更改 html 音频元素中的 src 时,即使 src 路径确实更改,实际音频也不会更改。我可以在开发工具中看到它发生。单击按钮时,我可以看到 src 更改,但正在播放的音频没有更改。如果音轨完成,则不会加载下一个音轨。无论 src 是什么,我听到的音频总是轨道 1。
我的另一个问题是 songBuilder() 返回未定义。我在我的语法中找不到任何错误,尽管它们必须存在。我使用 create-react-app 作为我的样板,因为我对 webpack 一无所知。我的地图问题是我对 JS 的理解有缺陷还是捆绑/构建发生了奇怪的事情?如果需要更多信息来回答这个问题,请告诉我。谢谢!
import React, { Component } from "react";
const songRepo = [
{
title: "The Silver Swan",
songLength: "0:13",
path: require("./songs/thesilverswan.mp3")
},
{
title: "Miracle Cure",
songLength: "0:12",
path: require("./songs/miraclecure.mp3")
},
{
title: "Miracle Cure",
songLength: "0:12",
path: require("./songs/miraclecure.mp3")
},
{
title: "Miracle Cure",
songLength: "0:12",
path: require("./songs/miraclecure.mp3")
}
];
export default class MusicPlayer extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
songBuilder() {
return songRepo.map((song, index) => (
<li
className={index % 2 === 0 ? "even song_wrapper" : "odd song_wrapper"}
>
<span className="song_number"> {index + 1}</span>
<span key={index + 1} className="song_title">
{song.title}
</span>
<span className="song_length">{song.songLength}</span>
</li>
));
}
playerClick(type) {
if (type === "next_song" && this.state.count < songRepo.length - 1) {
this.setState({ count: this.state.count + 1 });
} else if (type === "prev_song" && this.state.count > 0) {
this.setState({ count: this.state.count - 1 });
}
}
render() {
return (
<div className="player">
<div className="player_nav">
<div className="player_title">
<span className="song_number">{this.state.count + 1}</span>
<span className="song_title">
{songRepo[this.state.count].title}
</span>
<span className="song_length">
{songRepo[this.state.count].songLength}
</span>
</div>
<audio className="waveform" controls="controls">
<source src={songRepo[this.state.count].path} type="audio/mp3" />
</audio>
<div className="player_buttons">
<span
className="prev_song"
onClick={this.playerClick.bind(this, "prev_song")}
>
‹‹
</span>
<span> </span>
<span
className="next_song"
onClick={this.playerClick.bind(this, "next_song")}
>
››
</span>
</div>
<div>
<ul className="song_list">{songBuilder()}</ul>
</div>
</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
尝试将此方法称为
<ul className="song_list">{this.songBuilder}</ul>
Run Code Online (Sandbox Code Playgroud)
最初你称你的方法为
songBuilder() --returns "undefined" 因为它指向窗口
this.songBuilder -- 作为指向当前对象的这个点
如果您的函数是在对象中定义的,则直接从对象调用它会将其上下文设置为调用该函数的对象。
| 归档时间: |
|
| 查看次数: |
5777 次 |
| 最近记录: |