【问题标题】:With Styled Components how to only apply a style to small devices?使用 Styled Components 如何仅将样式应用于小型设备?
【发布时间】:2018-10-05 03:43:37
【问题描述】:

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

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 处理程序,但仅当断点很小,而不是中等或大时。

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

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

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

【问题讨论】:

  • 这不是一个样式组件问题,它只是一个关于在浏览器窗口低于一定大小时启用点击的问题。

标签: reactjs styled-components


【解决方案1】:

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

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。您单击处理程序将检查此布尔值。如果为假,则立即返回。

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

【讨论】:

  • 谢谢,但是“preview.bundle.js:112622 Uncaught ReferenceError: breakpoints is not defined”
猜你喜欢
  • 2020-08-18
  • 2020-04-04
  • 2021-11-01
  • 1970-01-01
  • 2018-01-18
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多