请查看代码。我想有条件地为 about 链接添加一些额外的样式,因此我将其添加到标签模板字符串的 ${} 内。这不会应用新样式。
我尝试过连接模板字符串。这也不起作用。
我无法在标签中设置 style={style},因为那样我将无法使用 :hover 样式。
import Link from 'next/link'
import { withRouter } from 'next/router'
const Header = ({ children, router, href }) => {
const isIndex = router.pathname === "/";
const isAbout = router.pathname === "/about";
return (
<div>
<Link href="/">
<a id="home">Timers</a>
</Link>
<Link href="/about">
<a id="about">About</a>
</Link>
<style jsx>{
`
a {
font-family: 'Montserrat Subrayada', sans-serif;
color: #ffffff;
text-decoration: none;
font-size: 24px;
padding: 2px;
margin-right: 30px;
}
a:hover {
color: #000000;
background-color: #ffffff;
border-radius: 2px;
}
${isAbout ? `
#about {
background-color: red;
color: #000000;
}
#about:hover {
background-color: blue;
color: #ffffff;
}
` : ``}
`
}</style>
</div>
)}
export default withRouter(Header)
如何应用条件样式?
最佳答案
解决方案是仅动态更改属性值,而不是在单个条件中添加整个新选择器,您必须为每个属性执行此操作,如下所示:
<style jsx>{
`
a {
font-family: 'Montserrat Subrayada', sans-serif;
color: #ffffff;
text-decoration: none;
font-size: 24px;
padding: 2px;
margin-right: 30px;
border-radius: 2px;
}
a:hover {
color: #000000;
background-color: #ffffff;
}
#home {
background-color: ${isHome ? "#ffffff" : ""};
color: ${isHome ? "#000000" : ""};
}
#about {
background-color: ${isAbout ? "#ffffff" : ""};
color: ${isAbout ? "#000000" : ""};
}
`
}</style>
(我在提问时找到了问题的答案,所以我想无论如何我都会将其与我的答案一起发布,以防其他人需要它)
关于javascript - 在 Next.js 中动态添加样式到 styled-jsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54917399/