【问题标题】:Changing font size with respect to the change in screen resolution using styled-components in react使用样式组件在反应中根据屏幕分辨率的变化更改字体大小
【发布时间】:2021-11-24 03:00:35
【问题描述】:

我正在使用样式化组件设计一个简单的反应应用程序。我正在努力让它更具响应性。

所以我创建了一个组件(广告),其属性值为宽度和高度。 根据宽度和高度值,字体大小应该会改变。

这就是我的广告组件的制作方法。

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

当屏幕尺寸发生变化时,我可以做些什么来重新渲染这个组件?

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

【问题讨论】:

    标签: reactjs responsive-design styled-components react-props


    【解决方案1】:

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

    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`};
    `; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多