首页 > 解决方案 > 在 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;
  }
}

标签: reactjssass

解决方案


这就是你可以这样做的方式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>
  );
}

原始代码框链接已使用此最新答案进行了更新。


推荐阅读