[英]How to apply CSS to body element if prop is present?
If the open prop value is true I want to apply a position fix to the body element, how can I achieve that using styled components?如果 open prop 值为 true 我想对 body 元素应用 position 修复,如何使用样式化组件来实现?
export const Navbar = styled.nav`
box-sizing: border-box;
overflow-y: scroll;
justify-content: center;
background: ${() => "#ffffff"};
height: 100vh;
text-align: left;
padding: 5rem 4rem 2rem;
top: 0;
left: 0;
transition: transform 0.3s ease-in-out;
transform: ${({ open }) => (open ? "translateX(0)" : "translateX(-110%)")};
body {
position: ${({ open }) => (open ? "fixed" : "absolute")};
}
I'm not familiar with react styled components but I doubt that the syntax with the nested body
tag is correct.我不熟悉 react 样式的组件,但我怀疑带有嵌套
body
标记的语法是否正确。
You could use a useEffect
hook inside your Navbar component though:不过,您可以在 Navbar 组件中使用
useEffect
挂钩:
useEffect(() => {
document.body.style.position = open ? 'fixed' : 'absolute';
}, [open]);
This will call the arrow function initially and whenever the open
prop changes.这将调用箭头 function 最初以及每当
open
道具更改时。
The right way is to use the library API as querying the document-object/DOM is an anti-pattern in React (that's why you using React in first place).正确的方法是使用库 API 因为查询文档对象/DOM 是 React 中的反模式(这就是您首先使用 React 的原因)。
See body style example:参见车身样式示例:
const GlobalStyle = createGlobalStyle`
body {
color: ${({ open }) => (open ? "red" : "blue")}
}
`;
export default function App() {
const [open, toggle] = useReducer((p) => !p, false);
return (
<>
Body Style Example
<GlobalStyle open={open} />
<button onClick={toggle}>toggle</button>
</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.