在react中使用style -components根据屏幕分辨率的变化改变字体大小



我正在设计一个使用样式组件的简单react应用程序。我在试着让它更有响应性。

所以我创建了一个组件(Ad)的宽度和高度的道具值。根据宽度和高度的值,字体大小应该改变。

这就是如何制作我的广告组件。

const AdContainer = styled.div`
max-width: ${props=>props.width};
max-height:  ${props=>props.height};
`;  
const Adp = styled.p`
font-size:  ${props=>props.width>"870px"?"24px":"16px"};
`;
function Ad({height,width}) {
return (
<AdContainer height={height} width={width}>
<AdTitle>Hello</AdTitle>
</AdContainer>
);
}

考虑这个父组件

function ProductPage() {
return (
<>
<Ad width={"1920px"} height={"600px"}/>
</>
);
}
export default ProductPage;

当我们传递width=1920pxheight=600px时,Adtitle的字体大小应该改为24px,因为这

const Adp = styled.p`
font-size:  ${props=>props.width>"870px"?"24px":"16px"};
`;

但不改变,坚持16px

如何在屏幕大小发生变化时呈现该组件?

或者是否有其他替代方案来解决这个问题,以便无论我在哪里使用这个广告组件,字体大小都应该根据给定的道具宽度和高度值而改变?

您试图将字符串与字符串作为数字进行比较。不要这样做。像这样做。

const Adp = styled.p`
font-size:  ${p => p.width > 870 ? "24px" : "16px"};
`;
// And pass the props like this
<Adp width={1920} height={600}/>
// AdContainer
const AdContainer = styled.div`
max-width: ${p => `${p.width}px`};
max-height:  ${p => `${p.height}px`};
`; 

最新更新