JSX
您可以使用 hono/jsx
以 JSX 語法撰寫 HTML。
儘管 hono/jsx
在客戶端上也能運作,但您可能會更常在伺服器端渲染內容時使用它。以下是一些與 JSX 相關,伺服器和客戶端皆通用的事項。
設定
要使用 JSX,請修改 tsconfig.json
tsconfig.json
:
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "hono/jsx"
}
}
或者,使用 pragma 指令
/** @jsx jsx */
/** @jsxImportSource hono/jsx */
對於 Deno,您必須修改 deno.json
而不是 tsconfig.json
{
"compilerOptions": {
"jsx": "precompile",
"jsxImportSource": "hono/jsx"
}
}
使用方式
index.tsx
:
import { Hono } from 'hono'
import type { FC } from 'hono/jsx'
const app = new Hono()
const Layout: FC = (props) => {
return (
<html>
<body>{props.children}</body>
</html>
)
}
const Top: FC<{ messages: string[] }> = (props: {
messages: string[]
}) => {
return (
<Layout>
<h1>Hello Hono!</h1>
<ul>
{props.messages.map((message) => {
return <li>{message}!!</li>
})}
</ul>
</Layout>
)
}
app.get('/', (c) => {
const messages = ['Good Morning', 'Good Evening', 'Good Night']
return c.html(<Top messages={messages} />)
})
export default app
片段
使用片段來群組多個元素,而無需新增額外節點
import { Fragment } from 'hono/jsx'
const List = () => (
<Fragment>
<p>first child</p>
<p>second child</p>
<p>third child</p>
</Fragment>
)
如果設定正確,您也可以使用 <></>
來撰寫。
const List = () => (
<>
<p>first child</p>
<p>second child</p>
<p>third child</p>
</>
)
PropsWithChildren
您可以使用 PropsWithChildren
來正確推斷函數組件中的子元素。
import { PropsWithChildren } from 'hono/jsx'
type Post = {
id: number
title: string
}
function Component({ title, children }: PropsWithChildren<Post>) {
return (
<div>
<h1>{title}</h1>
{children}
</div>
)
}
插入原始 HTML
要直接插入 HTML,請使用 dangerouslySetInnerHTML
app.get('/foo', (c) => {
const inner = { __html: 'JSX · SSR' }
const Div = <div dangerouslySetInnerHTML={inner} />
})
記憶化
使用 memo
記憶化計算出的字串來優化您的組件
import { memo } from 'hono/jsx'
const Header = memo(() => <header>Welcome to Hono</header>)
const Footer = memo(() => <footer>Powered by Hono</footer>)
const Layout = (
<div>
<Header />
<p>Hono is cool!</p>
<Footer />
</div>
)
上下文
透過使用 useContext
,您可以在組件樹的任何層級中全域共享數據,而無需透過 props 傳遞值。
import type { FC } from 'hono/jsx'
import { createContext, useContext } from 'hono/jsx'
const themes = {
light: {
color: '#000000',
background: '#eeeeee',
},
dark: {
color: '#ffffff',
background: '#222222',
},
}
const ThemeContext = createContext(themes.light)
const Button: FC = () => {
const theme = useContext(ThemeContext)
return <button style={theme}>Push!</button>
}
const Toolbar: FC = () => {
return (
<div>
<Button />
</div>
)
}
// ...
app.get('/', (c) => {
return c.html(
<div>
<ThemeContext.Provider value={themes.dark}>
<Toolbar />
</ThemeContext.Provider>
</div>
)
})
非同步組件
hono/jsx
支援非同步組件,因此您可以在組件中使用 async
/await
。如果您使用 c.html()
渲染它,它將自動等待。
const AsyncComponent = async () => {
await new Promise((r) => setTimeout(r, 1000)) // sleep 1s
return <div>Done!</div>
}
app.get('/', (c) => {
return c.html(
<html>
<body>
<AsyncComponent />
</body>
</html>
)
})
Suspense 實驗性
類似 React 的 Suspense
功能可用。如果您使用 Suspense
包裝非同步組件,則會先渲染 fallback 中的內容,一旦 Promise 被解析,將顯示等待的內容。您可以將其與 renderToReadableStream()
一起使用。
import { renderToReadableStream, Suspense } from 'hono/jsx/streaming'
//...
app.get('/', (c) => {
const stream = renderToReadableStream(
<html>
<body>
<Suspense fallback={<div>loading...</div>}>
<Component />
</Suspense>
</body>
</html>
)
return c.body(stream, {
headers: {
'Content-Type': 'text/html; charset=UTF-8',
'Transfer-Encoding': 'chunked',
},
})
})
ErrorBoundary 實驗性
您可以使用 ErrorBoundary
來捕獲子組件中的錯誤。
在下面的範例中,如果發生錯誤,它將顯示 fallback
中指定的內容。
function SyncComponent() {
throw new Error('Error')
return <div>Hello</div>
}
app.get('/sync', async (c) => {
return c.html(
<html>
<body>
<ErrorBoundary fallback={<div>Out of Service</div>}>
<SyncComponent />
</ErrorBoundary>
</body>
</html>
)
})
ErrorBoundary
也可以與非同步組件和 Suspense
一起使用。
async function AsyncComponent() {
await new Promise((resolve) => setTimeout(resolve, 2000))
throw new Error('Error')
return <div>Hello</div>
}
app.get('/with-suspense', async (c) => {
return c.html(
<html>
<body>
<ErrorBoundary fallback={<div>Out of Service</div>}>
<Suspense fallback={<div>Loading...</div>}>
<AsyncComponent />
</Suspense>
</ErrorBoundary>
</body>
</html>
)
})
與 html 中介軟體整合
結合 JSX 和 html 中介軟體以獲得強大的樣板功能。有關深入的詳細資訊,請查閱html 中介軟體文件。
import { Hono } from 'hono'
import { html } from 'hono/html'
const app = new Hono()
interface SiteData {
title: string
children?: any
}
const Layout = (props: SiteData) =>
html`<!doctype html>
<html>
<head>
<title>${props.title}</title>
</head>
<body>
${props.children}
</body>
</html>`
const Content = (props: { siteData: SiteData; name: string }) => (
<Layout {...props.siteData}>
<h1>Hello {props.name}</h1>
</Layout>
)
app.get('/:name', (c) => {
const { name } = c.req.param()
const props = {
name: name,
siteData: {
title: 'JSX with html sample',
},
}
return c.html(<Content {...props} />)
})
export default app
使用 JSX 渲染器中介軟體
JSX 渲染器中介軟體可讓您更輕鬆地使用 JSX 建立 HTML 頁面。
覆寫類型定義
您可以覆寫類型定義以新增自訂元素和屬性。
declare module 'hono/jsx' {
namespace JSX {
interface IntrinsicElements {
'my-custom-element': HTMLAttributes & {
'x-event'?: 'click' | 'scroll'
}
}
}
}