reactjs - 在 React 中设置响应式处理程序,然后在 scss 中使用它们
问题描述
我有一个自定义 Hook 可以检测应用程序是移动版还是桌面版。提供 2 个版本的组件可以工作,但我不知道如何将变量传递给 scss 文件。
在我的 app.js 中,我有几个基于@media (max-width: 768px)
scss 文件中修改的类。如果我只有一种样式但有多种样式,这会很好,我想找到一种方法在 React 中设置要使用的样式。
如何使用{windowSize}
将 JS 变量传递给 .scss 文件?如果我使用 styled-component 它会是什么样子?
import "./app.scss";
import useWindowSize from "./useWindowSize";
export default function App() {
const windowSize = useWindowSize();
return (
<div className="App">
<h1>Making the app responsive</h1>
<h2 className="TestTitle">{windowSize}</h2>
<p className="BoxWidth">Hello world</p>
</div>
);
}
样式如下所示:
$width: 768px;
$Colour1: rgb(0, 255, 213);
.BoxWidth {
background-color: green;
@media (max-width: $width) {
background-color: lightblue;
}
}
解决方案
这就是你可以这样做的方式styled-components
:
const Box = styled.div` // or 'p' depending on which element you want to use
background-color: green;
// Note that you are using a 'width' prop that needs to be passed in
@media (max-width: ${({ width }) => width}) {
background-color: lightblue;
}
`;
export default function App() {
const windowSize = useWindowSize();
return (
<div className="App">
...
// You pass the window size in as the width prop
<Box width={windowSize}>Hello world</Box>
</div>
);
}
查看您修改后的代码框
编辑
我们在聊天中澄清了这个问题。这是解决方案:
const commonStyles = { background: "pink", height: 100, margin: "0 auto" };
const SmallComponent = () => <div style={{ ...commonStyles, width: "100%" }} />;
const LargeComponent = () => (
<div style={{ ...commonStyles, width: "500px" }} />
);
const Box = styled.div`
color: white;
background-color: ${({ isMobile }) => (isMobile ? "green" : "lightblue")};
`;
export default function App() {
const windowSize = useWindowSize();
const isMobile = windowSize === "useMobileVersion";
return (
<div className="App">
<h1>Making the app responsive</h1>
<h2>{windowSize}</h2>
<Box isMobile={isMobile}>Hello world</Box>
{isMobile ? <SmallComponent /> : <LargeComponent />}
</div>
);
}
原始代码框链接已使用此最新答案进行了更新。
推荐阅读
- javascript - 试图让导航在本机反应的页面之间工作
- python - 打印文本文件的行号
- python - 填充和重塑熊猫数据框
- javascript - 前端开发人员面试编码问题:a 未定义,b 已定义?
- xml - Outlook Manifest 在 Web Outlook 中有效,无法在桌面 Outlook 中正确安装
- javascript - 通过使用 jQuery 删除类来关闭下拉菜单
- kotlin - 如何通过 Kotlin 在 Redshift JDBC PreparedStatement 中使用和设置数组
- sql-server - xml根在sql中重复多次?
- amazon-web-services - 审计 AWS 上的 k8s 集群事件
- swift - 如何在 SwiftUI tvOS 中检测“点击”手势