我有两个反应组件,可帮助我根据屏幕尺寸创建响应式布局。
第一个WindowDimensionsProvider:
import React, { createContext, useContext, useState, useEffect } from 'react';
const WindowDimensionsCtx = createContext(null);
const WindowDimensionsProvider = ({ children }) => {
const [dimensions, setDimensions] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
const handleResize = () => {
setDimensions({
width: window.innerWidth,
height: window.innerHeight
});
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return <WindowDimensionsCtx.Provider value={dimensions}>{children}</WindowDimensionsCtx.Provider>;
};
export default WindowDimensionsProvider;
export const useWindowDimensions = () => useContext(WindowDimensionsCtx);
第二个是ResponsiveLayout:
import { useWindowDimensions } from './WindowDiamensionProvider';
const ResponsiveLayout = ({ renderMobile, renderDesktop, renderTablet }) => {
const { width } = useWindowDimensions();
if (width <= 767) {
return renderMobile();
// eslint-disable-next-line no-else-return
} else if (width > 767 && width < 991) {
return renderTablet();
} else {
return renderDesktop();
}
};
export default ResponsiveLayout;
当我在主屏幕中使用ResponsiveLayout组件呈现不同的布局时,一切都正常。
<ResponsiveLayout
style={{ marginRight: '0' }}
renderDesktop={() => (
<div>
This is desktop
</div>
)}
renderMobile={() => (
<div>
This is mobile
</div>
)}
renderTablet={() => (
<div>
And this is tablet
</div>
)}
/>
的崩溃
我可以轻松地使用其他一些库或api来达到相同的结果,但是肯定有一些我不了解React或我做错了的事情。我希望对它有更好的了解。
我们将不胜感激。