css 辅助工具
css 辅助工具 - hono/css - 是 Hono 内置的 CSS in JS(X)。
您可以在名为 css 的 JavaScript 模板字面量中编写 CSS in JSX。css 的返回值将是类名,它被设置为类属性的值。然后,<Style /> 组件将包含 CSS 的值。
导入
ts
import { Hono } from 'hono'
import { css, cx, keyframes, Style } from 'hono/css'css 实验性
您可以在 css 模板字面量中编写 CSS。在本例中,它使用 headerClass 作为 class 属性的值。不要忘记添加 <Style />,因为它包含 CSS 内容。
ts
app.get('/', (c) => {
const headerClass = css`
background-color: orange;
color: white;
padding: 1rem;
`
return c.html(
<html>
<head>
<Style />
</head>
<body>
<h1 class={headerClass}>Hello!</h1>
</body>
</html>
)
})您可以使用 嵌套选择器 & 来设置伪类,例如 :hover。
ts
const buttonClass = css`
background-color: #fff;
&:hover {
background-color: red;
}
`扩展
您可以通过嵌入类名来扩展 CSS 定义。
tsx
const baseClass = css`
color: white;
background-color: blue;
`
const header1Class = css`
${baseClass}
font-size: 3rem;
`
const header2Class = css`
${baseClass}
font-size: 2rem;
`此外,${baseClass} {} 语法允许嵌套类。
tsx
const headerClass = css`
color: white;
background-color: blue;
`
const containerClass = css`
${headerClass} {
h1 {
font-size: 3rem;
}
}
`
return c.render(
<div class={containerClass}>
<header class={headerClass}>
<h1>Hello!</h1>
</header>
</div>
)全局样式
名为 :-hono-global 的伪选择器允许您定义全局样式。
tsx
const globalClass = css`
:-hono-global {
html {
font-family: Arial, Helvetica, sans-serif;
}
}
`
return c.render(
<div class={globalClass}>
<h1>Hello!</h1>
<p>Today is a good day.</p>
</div>
)或者您可以在 <Style /> 组件中使用 css 字面量编写 CSS。
tsx
export const renderer = jsxRenderer(({ children, title }) => {
return (
<html>
<head>
<Style>{css`
html {
font-family: Arial, Helvetica, sans-serif;
}
`}</Style>
<title>{title}</title>
</head>
<body>
<div>{children}</div>
</body>
</html>
)
})keyframes 实验性
您可以使用 keyframes 来编写 @keyframes 的内容。在本例中,fadeInAnimation 将是动画的名称。
tsx
const fadeInAnimation = keyframes`
from {
opacity: 0;
}
to {
opacity: 1;
}
`
const headerClass = css`
animation-name: ${fadeInAnimation};
animation-duration: 2s;
`
const Header = () => <a class={headerClass}>Hello!</a>cx 实验性
cx 合并了两个类名。
tsx
const buttonClass = css`
border-radius: 10px;
`
const primaryClass = css`
background: orange;
`
const Button = () => (
<a class={cx(buttonClass, primaryClass)}>Click!</a>
)它还可以组合简单的字符串。
tsx
const Header = () => <a class={cx('h1', primaryClass)}>Hi</a>提示
如果您使用 VS Code,则可以使用 vscode-styled-components 来获取 css 标记字面量的语法高亮和智能感知。

