style={window.innerWidth<='750 px' ?{myStyle}:{}}
有人能帮我吗?我想根据窗口宽度设置样式。CCD_ 1是一种状态。
嘿,这是我写的一个钩子,用于获取窗口尺寸,然后你可以在带有三元运算符的样式标签中使用钩子的宽度来显示不同的样式
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height,
};
}
/**
* @returns {object} {width, height}
*/
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
);
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return windowDimensions;
}
使用
const Component = () => {
const {width, height} = useWindowDimensions()
return <div style ={width > 750 ? {Place >750 styles here} : {Place < 750 styles here} }></div>
}
实现这一点的最佳方法是使用自定义挂钩。当窗口大小改变时,这个钩子可以得到当前窗口width
和height
。
事件侦听器在安装组件以更新状态时注册,在卸载组件时安全删除。
import { useState, useEffect } from "react";
// hook to get window size dynamically
const useWindowSize = () => {
// Initialize state with undefined width/height so server and client renders match
// Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined
});
useEffect(() => {
// only execute all the code below in client side
if (typeof window !== "undefined") {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,
height: window.innerHeight
});
}
// Add event listener
window.addEventListener("resize", handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
return () => window.removeEventListener("resize", handleResize);
}
}, []); // Empty array ensures that effect is only run on mount
return windowSize;
};
export default useWindowSize;
此解决方案也可以与服务器渲染完美配合。将useWindowSize
挂钩导入到所需的组件中,并根据需要使用大小。
import useWindowSize from '/path/to/hooks/useWindowSize'
const MyComp = () => {
const size = useWindowSize();
return <div style={style={size.width<='750 px' ?{myStyle}:{}}}></div>;
};
export default MyComp;