点击显示一个图片,再次点击显示另外一个图片

4

我正在尝试制作一个静音和取消静音的功能。但是我不确定如何通过if语句显示图像路径。 目前只是一个文本按钮,点击后会在静音和取消静音之间切换。

  mute() {
const video = this.refs.video;
const muteButton = this.refs.mute;

if (video.muted === false) {
  video.muted = true;
  muteButton.innerHTML = "Unmute"; // this should be where the image is linked
} else {
  video.muted = false;
  muteButton.innerHTML = "Mute"; // this should be where the image is linked
}

}

<Button ref="mute" onClick={() => this.mute()} color="danger">
     Unmute
</Button>
4个回答

2
你可以使用三元运算符。
const muteButton = this.refs.mute;

<Button ref="mute" onClick={() => this.mute()} color="danger">
     { video.muted ? muteButton.innerHTML = "Unmute" : muteButton.innerHTML = "Mute" }
</Button>

请不要滥用 refs,因为在这里 https://reactjs.org/docs/refs-and-the-dom.html 中已经说明了。您可以轻松地通过React的状态来管理它。 - zhuber
是的,但这并不是一个困难的解决方案。这非常简单。 - Pushprajsinh Chudasama

1

由于您正在使用React,因此不应该为此类事情使用innerHTML。只需在JSX中使用三元运算符即可:

<Button ref="mute" onClick={() => this.mute()} color="danger">
     { video.muted ? 'Unmute' : 'Mute' }
</Button>

同样的事情也适用于图片。您可以直接放置特定的 URL:
<img src={ video.muted ? mutedUrl : unmutedUrl } />

或者你可以使用CSS类:

<Button className={ video.muted ? 'muted' : 'unmuted' } ...>
  ...
</Button>

此外,我发现视频也是一个元素。最好将状态保存在this.state中。
toggle() {
  const { muted } = this.state;

  this.setState({ muted: !muted });
}

render() {
  const { muted } = this.state;

  ...
    <Video muted={ muted } ...>
      ...
    </Video>
    ...
    <Button ...>
      { muted ? 'Unmute' : 'Mute' }
    </Button>
  ...
}

您可以通过绑定 toggle() 函数来进一步改进代码:

// this option is better
toggle = () => {
  ...
};

// or in your constructor add
constructor(props) {
  ...

  this.toggle = this.toggle.bind();
}

然后,您将能够在每次渲染时摆脱新的匿名函数:
<Button onClick={ this.toggle } ...>
  ...
</Button>

1
你需要通过react的state来跟踪你的当前状态。请参见这个sandbox

1
你可以通过创建两个CSS类来保持JavaScript逻辑和图形之间的区别:
.mute{
   background: //your image with its style
}
.unmute{
  background: //same as above
}

然后在JavaScript中:
  function mute() {
     const video = this.refs.video;
     const muteButton = this.refs.mute;

     if (video.muted === false) {
        video.muted = true;
        muteButton.classList.remove("unmute");
        muteButton.classList.add("mute");
     } else {
        video.muted = false;
        muteButton.classList.remove("mute");
        muteButton.classList.add("unmute");
     }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接