Reactjs 的媒体查询语法

新手上路,请多包涵

如何在 Reactjs 中执行以下 CSS 媒体查询?

 .heading {
  text-align: right;
  /* media queries */
  @media (max-width: 767px) {
    text-align: center;
  }
  @media (max-width: 400px) {
    text-align: left;
  }
}

我尝试了以下方法,但它引发了语法错误并且无法编译。

 heading: {
  textAlign: 'right',
  @media (maxWidth: '767px') {
    textAlign: 'center';
  }
  @media (maxWidth: '400px') {
    textAlign: 'left';
  }
}

原文由 Let Me Tink About It 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 991
2 个回答

如果您有特殊情况,当您需要在您的 react 应用程序中获取媒体查询结果时(例如,您想在移动版本中显示某些组件),您可以使用 react-responsivereact-media-hook 等帮助程序。

原文由 Ilya Lesik 发布,翻译遵循 CC BY-SA 4.0 许可协议

可以 在 React 中进行媒体查询:

 import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props)
    this.state = { matches: window.matchMedia("(min-width: 768px)").matches };
  }

  componentDidMount() {
    const handler = e => this.setState({matches: e.matches});
    window.matchMedia("(min-width: 768px)").addEventListener('change', handler);
  }
  render() {
    return (
      <div >
      {this.state.matches && (<h1>Big Screen</h1>)}
      {!this.state.matches && (<h3>Small Screen</h3>)}
      </div>
    );
  }
}

export default App;

https://stackblitz.com/edit/react-cu8xqj?file=src/App.js


2021 年 9 月 10 日编辑:将 addListener 替换为 addEventListener 因为前者已 弃用。感谢 John Galt 通过发表评论让我们知道。

原文由 Ferit 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题