Components

<Switch> / <Match>

编辑此页面

当有超过2个互斥条件时非常有用。这是 if-else-if-else-if-else-... 链的一个更灵活的版本。

import { Switch, Match } from "solid-js"
import type { MatchProps, JSX } from "solid-js"
function Switch(props: {
fallback?: JSX.Element
children: JSX.Element
}): () => JSX.Element
type MatchProps<T> = {
when: T | undefined | null | false
children: JSX.Element | ((item: T) => JSX.Element)
}
function Match<T>(props: MatchProps<T>)

这个组件的一个超级简单实现可能是:

function Switch(props) {
let children = props.children
if (!Array.isArray(children)) children = [children]
for (let i = 0; i < children.length; i++) {
const child = children[i]
if (child.props.when) return child
}
return props.fallback
}

例如,它可以用于执行基本路由:

<Switch fallback={<div>未找到</div>}>
<Match when={state.route === "home"}>
<Home />
</Match>
<Match when={state.route === "settings"}>
<Settings />
</Match>
</Switch>

Match 还支持函数子组件以作为键控流。


属性

Switch

名称类型默认值描述
fallbackJSX.Elementundefined当没有 Match 组件的 when 属性为真时渲染的后备元素。

Match

名称类型默认值描述
whenT | undefined | null | falseundefined要检查的条件。如果为真,将渲染 children
报告此页面问题