【问题标题】:Is it possible to use Style System's breakpoints inside a Styled-Component?是否可以在样式组件中使用样式系统的断点?
【发布时间】:2019-12-26 02:16:45
【问题描述】:

我想在样式化组件中使用样式化系统的断点和大小调整机制。

目前,我必须使用“react-media”,它解决了我的问题,但是这个解决方案带有大量的代码重复。这是我目前根据屏幕大小设置 StyledComponent 的边框半径的解决方案:

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

是否可以获取当前断点索引? 我可以这样写吗:

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

【问题讨论】:

  • 这篇文章可能对stackoverflow.com/questions/50009139/…有帮助
  • 谢谢 Bonnie,这不是我要找的,但它可以解决问题。
  • 如果您(真的)想要这样做,您需要自己跟踪浏览器宽度。例如,您的 App 组件中的一个钩子会更新全局状态(如 redux )并在您需要时获取该数据(如果是 redux,则为 connect )。我实际上认为您不需要那个,边界半径也可以通过媒体查询进行调整

标签: css reactjs media-queries styled-components rebass


【解决方案1】:

阅读this 他们建议您在查询中注入断点并将它们放入主题中。然后你不能像这样访问它们:

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

然而,这个解决方案使用 css 来改变样式(但我认为应该这样做)。

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 2019-08-23
    • 2021-07-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2019-11-08
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多