使用样式化组件如何仅将样式应用于小型设备? [英] With Styled Components how to only apply a style to small devices?

查看:31
本文介绍了使用样式化组件如何仅将样式应用于小型设备?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的样式组件主题目前包括:

My styled components theme currently includes:

const breakpoints = {
  medium: '640px',
  large: '1080px',
};

const MyContainer = styled.div`
  // Default mobile stylings
  ${({ theme }) => theme.media.medium`
     // CSS goes here
  `}

  ${({ theme }) => theme.media.large`
     // CSS goes here
  `}
`;

在我的 React 组件中,我需要一个项目的 onClick 处理程序,但仅当断点很小,而不是中或大时才需要.

In my react component, I need an onClick handler for an item but ONLY when the breakpoint is small, not medium or large.

在我的反应组件中,由于某种原因,我无法弄清楚...

In my react component, for some reason, I can not figure this out...

const MyC = class extends React.Component {
  render() {
    console.log(this.props.theme);
    ....
  }
};

在使用样式化组件处理断点时,如何通知我的 React 组件当前断点的大小是否较小,然后才使用 onClick 处理程序?

While using Styled Components to handle breakpoints, how can I inform my React Component if the current breakpoint is currently size small and to only then use an onClick handler?

推荐答案

您需要使用 javascript 来处理此问题.将此添加到您的组件中:

You need to handle this with javascript. Add this to your component:

isEnabled = true;

calcButtonState = () => {
  if(window.innerWidth < breakpoints.medium) {
    this.isEnabled = false;
  } else {
    this.isEnabled = true;
  }    
}

handleButtonClick = () => {
   if(this.isEnabled === false) {
     return;
   }
}

componentDidMount() {
  this.calcButtonState();

  window.addEventListener('resize', this.calcButtonState);
}

componentWillUnmount() {
  window.removeEventListener('resize', this.calcButtonState);
}

这基本上是将布尔值设置为 true,如果您的窗口大于中等,如果窗口较小,则将其设置为 false.您单击处理程序将检查此布尔值.如果为false,则立即返回.

What this basically does is set a boolean to true, if your window with is larger than medium, and if it is smaller, set it to false. You click handler will then check for this boolean. If it is false, it will return immediately.

请在此处对调整大小事件使用某种去抖动功能.

Please also use some sort of debounce function here for the resize event.

这篇关于使用样式化组件如何仅将样式应用于小型设备?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆