简体   繁体   English

显示/隐藏react.js使用REF多个按钮

[英]Show/hide multiple buttons using ref in react.js

I have list of songs with play button. 我有带有播放按钮的歌曲列表。 I want to toggle button text to play/pause accordingly. 我想切换按钮文字以相应地播放/暂停。

I have set ref for play/pause <span> and trying to hide/show on button click. 我已将播放/暂停<span>设置为参考,并试图在单击按钮时隐藏/显示。

 this.refs.play.hide().

But this is giving error 但这给了错误

Uncaught TypeError: _this.refs.play.hide is not a function at Song._this.play 未捕获的TypeError:_this.refs.play.hide不是Song._this.play的函数

Here is my react component code. 这是我的React组件代码。

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>
    );
  }
}

Player.js 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 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>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM