Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单击“显示一个图像”,单击“显示另一个图像”_Javascript_Reactjs - Fatal编程技术网

Javascript 单击“显示一个图像”,单击“显示另一个图像”

Javascript 单击“显示一个图像”,单击“显示另一个图像”,javascript,reactjs,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

我正在尝试创建一个静音和取消静音功能。但我不确定如何通过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
}
}

this.mute()}color=“danger”>
取消静音

因为您使用的是React,所以不应该将
innerHTML
用于此类内容。只需在JSX中使用三元运算符即可:

this.mute()}color=“danger”>
{video.Mute?'Unmute':'Mute'}
图像也是如此。您可以直接放置特定的url:


或者您可以使用CSS类:


...
而且,正如我所看到的,视频也是一个元素。最好将状态保持在
this.state

toggle(){
const{mute}=this.state;
this.setState({mute:!mute});
}
render(){
const{mute}=this.state;
...
...
...
{静音?'Unmute':'Mute'}
...
}
通过绑定
toggle()
函数,您可以进一步改进代码:

//此选项更好
切换=()=>{
...
};
//或者在构造函数中添加
建造师(道具){
...
this.toggle=this.toggle.bind();
}
然后,您将能够在每个渲染上删除新的匿名函数:


...

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

您需要通过react跟踪当前状态。请看这个。

您可以使用三元运算符

const muteButton = this.refs.mute;

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

请不要像这里所说的那样过度使用引用。您可以使用reacts state.Yaa轻松地管理此问题,但这不是一个困难的解决方案。这很简单。
const muteButton = this.refs.mute;

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