简体   繁体   中英

Is it possible to use Style System's breakpoints inside a Styled-Component?

I would like to use styled-system's breakpoint and sizing mechanism inside a styled component.

Currently, I have to use 'react-media', which solves my problem, but this solution comes with a big amount of code duplication. Here is my current solution to set a StyledComponent's border-radius based on the screen size:

import React from 'react'
import styled from 'styled-components'
import theme from '../../theme'
import Media from 'react-media'

const StyledImg = styled.img`
  border-radius: ${props => (props.size / 4)};
`

function ProfileImage (props) {
  const breakpoint = theme.breakpoints[0]

  return <Media query={`(min-width: ${breakpoint})`}>
      {matches =>
        matches ? (
        <StyledImg size={props.size[1]} src={props.src} />
      ) : (
        <StyledImg size={props.size[0]} src={props.src} />
      )
    }
  </Media>
}

function ProfileCard (props) {
  return <Box bg='grey' width={1}>
    <ProfileImage width={[10, 20]} src={props.src}>
  </Box>
}

export default ProfileImage

Is it possible to get the current breakpoint index? Can I write something like this:

const StyledImg = styled.img`
  border-radius: ${props => (props.size[theme.currentBreakpointIndex] / 4)};
`

function ProfileImage (props) {
  return <StyledImg {...props} />
}

function ProfileCard (props) {
  return <Box bg='grey' width={1}>
    <ProfileImage size={[10, 20]} src={props.src}>
  </Box>
}

export default ProfileImage

Reading this they suggest you inject breakpoints into queries and put them in the theme. You cant then access them like this:

styled.div`
   ${({theme: {mediaQueries: {small}}}) => small} {
       color: red;
   }
`

This solution uses css to change styles however (but in my opinion that's how it should be done).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM