https://github.com/react-container-query/react-container-query
npm install react-container-query
import { ContainerQuery, useContainerQuery } from 'react-container-query';
// 媒体查询
const query = {
'screen-xs': {
maxWidth: 575,
},
'screen-sm': {
minWidth: 576,
maxWidth: 767,
},
'screen-md': {
minWidth: 768,
maxWidth: 991,
},
'screen-lg': {
minWidth: 992,
maxWidth: 1199,
},
'screen-xl': {
minWidth: 1200,
},
};
function App() {
return (
<ContainerQuery query={query}>
{params => <div className={classNames(params)}>{layout}</div>}
</ContainerQuery>
);
}
useContainerQuery
import React from 'react';
import { useContainerQuery } from 'react-container-query';
const query = {
'width-between-400-and-599': {
minWidth: 400,
maxWidth: 599,
},
'width-larger-than-600': {
minWidth: 600,
},
};
const MyCustomWrapper = React.forwardRef((props, ref) => {
// MyCustomWrapper really renders a div which wraps the children.
// Setting the ref on it allows container query to measure its size.
return <div ref={ref}>{props.children}</div>
});
const MyComponent = () => {
const [params, containerRef] = useContainerQuery(query);
return <MyCustomWrapper ref={containerRef} className={classnames(params)}>the box</div>;
};