我有一个styled-component
,我只想在屏幕尺寸大于480时才呈现。我尝试通过获取对元素的引用并将其禁用来进行渲染。但这没用。我将display
属性设置为none
,但是按钮仍然可以单击。
这是我的代码
console.log(window.screen.width);
if(window.screen.width <= 480) {
var a = document.getElementsByClassName("Button1")
...
...
...
...
}
return (
<>
<div className="control">
<Circle onClick={handleVideoToggle}>
<img src={video ? Video : VideoOff} />
</Circle>
<Circle onClick={handleAudioToggle}>
<img src={audio ? Mic : MicOff} />
</Circle>
<Circle onClick={handleScreenToggle}>
<img className = "Button1" src={screen ? Screen : ScreenOff} />
</Circle>
<Circle onClick={handleCallDisconnect}>
<img src={End} />
</Circle>
</div>
</>
);
};
export default Controls;
const
Circle = styled.div`
width: 45px;
height: 45px;
border-radius: 50%;
display: flex;
cursor: pointer;
:not(:first-child) {
margin-left: 20px;
}
`,
Image = styled.img`
max-width: 100%;
width: 45px;
margin: 0 auto;
`;
答案 0 :(得分:0)
删除if语句,使其可用于CSS媒体查询:
const Circle = styled.div`
width: 45px;
height: 45px;
border-radius: 50%;
display: flex;
cursor: pointer;
@media only screen and (max-width: 480px){
display: none;
}
:not(:first-child) {
margin-left: 20px;
}
`,
它仍然是可单击的,因为您为Curcle组件(而非img)设置了OnClick处理程序
答案 1 :(得分:0)
您可以删除顶部的“ if”块。您可以有条件地在返回的内容中包含Circle / Button,如下所示:
const isSmall = window.screen.width <= 480;
return (
<>
<div className="control">
<Circle onClick={handleVideoToggle}>
<img src={video ? Video : VideoOff} />
</Circle>
<Circle onClick={handleAudioToggle}>
<img src={audio ? Mic : MicOff} />
</Circle>
{!isSmall && (<Circle onClick={handleScreenToggle}>
<img className = "Button1" src={screen ? Screen : ScreenOff} />
</Circle>)
}
<Circle onClick={handleCallDisconnect}>
<img src={End} />
</Circle>
</div>
</>
);
答案 2 :(得分:0)
您可以按如下所示有条件地渲染StyledComponent。但是对于引用元素,您可以使用react ref
代替document.getElementsByClassName("Button1")
。
console.log(window.screen.width);
const isAbove480 = window.screen.width > 480;
return (
<>
<div className="control">
<Circle onClick={handleVideoToggle}>
<img src={video ? Video : VideoOff} />
</Circle>
<Circle onClick={handleAudioToggle}>
<img src={audio ? Mic : MicOff} />
</Circle>
{ isAbove480 ? (<Circle onClick={handleScreenToggle}>
<img className = "Button1" src={screen ? Screen : ScreenOff} />
</Circle>) : null }
<Circle onClick={handleCallDisconnect}>
<img src={End} />
</Circle>
</div>
</>
);
};
export default Controls;
const
Circle = styled.div`
width: 45px;
height: 45px;
border-radius: 50%;
display: flex;
cursor: pointer;
:not(:first-child) {
margin-left: 20px;
}
`,
Image = styled.img`
max-width: 100%;
width: 45px;
margin: 0 auto;
`;