【发布时间】: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