簡體   English   中英

是否可以在樣式組件內使用樣式系統的斷點?

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

我想在樣式組件中使用樣式系統的斷點和大小調整機制。

目前,我必須使用'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

閱讀本文,他們建議您將斷點注入查詢並將它們放在主題中。 然后你不能像這樣訪問它們:

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

但是,此解決方案使用 css 來更改樣式(但在我看來,應該這樣做)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM