我有播放按钮的歌曲列表。我想切换按钮文本以相应地播放/暂停。
我已设置参考播放/暂停<span>
并试图隐藏/显示按钮点击。
this.refs.play.hide().
但这是错误
未捕获的TypeError:_this.refs.play.hide不是函数 在Song._this.play
这是我的反应组件代码。
class Song extends React.Component {
play = (event) => {
this.refs.play.hide()
console.log(this.refs.play);
}
render() {
return (
<div>
<ul>
<li>Song 1 <button onClick={this.play}><span ref="play">play</span> <span className='hide' ref="pause"> Pause</span></button></li>
<li>Song 2 <button onClick={this.play}><span ref="play">play</span> <span className='hide' ref="pause"> Pause</span></button></li>
<li>Song 3 <button onClick={this.play}><span ref="play">play</span> <span className='hide' ref="pause"> Pause</span></button></li>
</ul>
</div>
);
}
}
答案 0 :(得分:0)
Player.js
import React, { Component } from "react";
export default class Player extends Component {
constructor(props) {
super(props);
this.state = {
isPlaying: false
};
}
togglePlay = () => {
this.setState({
isPlaying: !this.state.isPlaying
});
};
render() {
return (
<div>
{/* actual player logic {this.props.songurl} */}
<span>{this.props.songName}</span>
<button onClick={() => this.togglePlay()}>
{this.state.isPlaying ? "Pause" : "Play"}
</button>
</div>
);
}
}
PlayerList.js
import React, { Component } from "react";
import Player from "./Player";
export default class SongList extends Component {
render() {
const songs = [
{
name: "song 1",
url: "google.com"
},
{
name: "song 2",
url: "google.com"
},
{
name: "song 3",
url: "google.com"
},
{
name: "song 4",
url: "google.com"
},
{
name: "song 5",
url: "google.com"
},
{
name: "song 6",
url: "google.com"
}
];
return (
<div>
{songs.map((song, key) => (
<Player key={key} name={song.name} url={song.url} />
))}
</div>
);
}
}