我知道有很多方法可以在没有JSS的情况下做到这一点,但是这个范例似乎让它变得非常困难:
const Backdrop = () => {
const {height, width} = useWindowSize()
const css = makeStyles(() => createStyles({
root : {
backgroundColor: 'black',
backgroundImage: 'url(/img/bg.jpg)',
height, // this value should update when window size changes
width,
position:'fixed',
}
}))()
return <div className={css.root}>
</div>
}更新:我复制粘贴了一种方式来实现这个功能,但是与传统的CSS相比,它的代码太多了
const [_windowSize, $_windowSize] = useState({ width: window.innerWidth, height: window.innerHeight })
const handler = () => $_windowSize({ width: window.innerWidth, height: window.innerHeight })
useEffect(() => {
window.addEventListener("resize", handler)
return () => window.removeEventListener("resize", handler)
}, [])
return _windowSize
}
const Backdrop = () => {
useWindowSize()
const css = makeStyles(() => createStyles({
root : {
backgroundColor: 'black',
backgroundImage: 'url(/img/bg.jpg)',
backgroundSize: 'cover',
height: () => window.innerHeight,
width: () => window.innerWidth,
position:'fixed',
}
}))()
return <div className={css.root}></div>
}不知何故,makeStyles知道DOM中的每个更新。这真的很不直观。
发布于 2020-11-06 15:54:08
你可能需要这套西装吗?
const { height, width } = useWindowDimensions();
const style = {
root : {
backgroundColor: 'black',
backgroundImage: 'url(/img/bg.jpg)',
backgroundSize: 'cover',
height: height,
width: width,
position:'fixed'
}
}return <div style={style.root}></div>useWindowDimensions是一种自定义效果,定义如下:
/**
* Returns window dimensions, listening to resize event.
*
* Example:
*
* const Component = () => {
* const { height, width } = useWindowDimensions();
* }
*/
export function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
);
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}其效果是监听窗口调整大小并更新{width, height}状态,从而导致干净的重新渲染。
https://stackoverflow.com/questions/64710084
复制相似问题