https://github.com/react-container-query/react-container-query

  1. npm install react-container-query

image.png

  1. import { ContainerQuery, useContainerQuery } from 'react-container-query';
  2. // 媒体查询
  3. const query = {
  4. 'screen-xs': {
  5. maxWidth: 575,
  6. },
  7. 'screen-sm': {
  8. minWidth: 576,
  9. maxWidth: 767,
  10. },
  11. 'screen-md': {
  12. minWidth: 768,
  13. maxWidth: 991,
  14. },
  15. 'screen-lg': {
  16. minWidth: 992,
  17. maxWidth: 1199,
  18. },
  19. 'screen-xl': {
  20. minWidth: 1200,
  21. },
  22. };
  23. function App() {
  24. return (
  25. <ContainerQuery query={query}>
  26. {params => <div className={classNames(params)}>{layout}</div>}
  27. </ContainerQuery>
  28. );
  29. }

useContainerQuery

  1. import React from 'react';
  2. import { useContainerQuery } from 'react-container-query';
  3. const query = {
  4. 'width-between-400-and-599': {
  5. minWidth: 400,
  6. maxWidth: 599,
  7. },
  8. 'width-larger-than-600': {
  9. minWidth: 600,
  10. },
  11. };
  12. const MyCustomWrapper = React.forwardRef((props, ref) => {
  13. // MyCustomWrapper really renders a div which wraps the children.
  14. // Setting the ref on it allows container query to measure its size.
  15. return <div ref={ref}>{props.children}</div>
  16. });
  17. const MyComponent = () => {
  18. const [params, containerRef] = useContainerQuery(query);
  19. return <MyCustomWrapper ref={containerRef} className={classnames(params)}>the box</div>;
  20. };