项目作者: ThekhoN

项目描述 :
styled-components theme with mediaQueryBreakPoints
高级语言: JavaScript
项目地址: git://github.com/ThekhoN/styled-components-with-themes-and-mediaQueryBreakPoints.git


This project was bootstrapped with Create React App.

Available Scripts

In the project directory, you can run:

yarn start

Runs the app in the development mode.

Open http://localhost:3000 to view it in the browser.

The page will reload if you make edits.

You will also see any lint errors in the console.

Theme Provider with Media Query Breakpoints

MyHeader.js

  1. import styled from "styled-components/macro";
  2. const MyHeader = styled.h2`
  3. text-align: center;
  4. padding: 1rem 0;
  5. /* accessible via props */
  6. color: ${props => {
  7. return `${props.theme.colors.link}`;
  8. }};
  9. /* destructuring theme from props */
  10. font-family: ${({ theme }) => `${theme.fonts.main}`};
  11. /* media queries */
  12. ${({ theme }) =>
  13. `
  14. @media (min-width:${theme.mqBreakPoints.mobileS}) {
  15. color: orange;
  16. }
  17. @media (min-width:${theme.mqBreakPoints.mobileM}) {
  18. color: pink;
  19. }
  20. @media (min-width:${theme.mqBreakPoints.mobileL}) {
  21. color: red;
  22. }
  23. @media (min-width:${theme.mqBreakPoints.mobileL}) {
  24. color: red;
  25. }
  26. @media (min-width:${theme.mqBreakPoints.tablet}) {
  27. color: purple;
  28. }
  29. @media (min-width:${theme.mqBreakPoints.laptop}) {
  30. color: olive;
  31. }
  32. `}
  33. `;
  34. export default MyHeader;

ThemeContainer.js

  1. import React from "react";
  2. import { ThemeProvider } from "styled-components";
  3. const theme = {
  4. colors: {
  5. link: "#08f",
  6. separator: "#d9d9d9",
  7. text: "#808080",
  8. textLight: "#929292"
  9. },
  10. fonts: {
  11. main: [
  12. "source-code-pro",
  13. "Menlo",
  14. "Monaco",
  15. "Consolas",
  16. "Courier New",
  17. "monospace"
  18. ]
  19. },
  20. fontSizes: {
  21. small: "12px",
  22. medium: "14px",
  23. large: "20px"
  24. },
  25. mqBreakPoints: {
  26. mobileS: "320px",
  27. mobileM: "375px",
  28. mobileL: "425px",
  29. tablet: "768px",
  30. laptop: "1024px",
  31. laptopL: "1440px",
  32. desktop: "2560px"
  33. }
  34. };
  35. const ThemeContainer = ({ children }) => (
  36. <ThemeProvider theme={theme}>{children}</ThemeProvider>
  37. );
  38. export default ThemeContainer;

App.js

  1. import React from "react";
  2. import MyHeader from "./components/MyHeader";
  3. import ThemeContainer from "./ThemeContainer";
  4. function App() {
  5. return (
  6. // Common Theme
  7. <ThemeContainer>
  8. <MyHeader>Styled Components FYI!</MyHeader>
  9. </ThemeContainer>
  10. );
  11. }
  12. export default App;