OnClick显示一张图片,onClick显示另一张图片

时间:2019-10-04 08:10:12

标签: javascript reactjs

我正在尝试设置静音和取消静音功能。但是我不确定如何通过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 个答案:

答案 0 :(得分:2)

您可以使用三元运算符。

const muteButton = this.refs.mute;

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

答案 1 :(得分:1)

由于您使用的是React,因此请勿使用innerHTML。只需在您的JSX中使用三元运算符即可实现这一目的:

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

与图像相同。您可以直接输入特定的网址:

<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>

答案 2 :(得分:1)

您可以在javascript逻辑和图形之间进行区分的方法是创建两个CSS类:

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

答案 3 :(得分:1)

您需要通过react的state来跟踪当前状态。请参阅此sandbox