Button
执行动作,显示它正在工作,并在禁用时仍可聚焦。
Button 渲染一个原生 button,并补上它自己做不到的事:异步动作运行时它保持待处理,所以表单不会提交两次;它向屏幕阅读器播报缓慢的动作;禁用时仍可聚焦;渲染成链接时也保持相同的行为。如果只是需要一个普通的点击处理函数,原生 button 就够了。
import { Button } from "@ui-sdk/solid/button"
import { useLog } from "./log"
function Example() {
const log = useLog()
return <Button onClick={() => log("Pressed")}>Button</Button>
}
export { Example }安装
npm install @ui-sdk/solid @ui-sdk/core用法
用 onClick 执行一个动作。Button 默认渲染一个 type="button" 的原生 <button>。
import { Button } from "@ui-sdk/solid/button"
;<Button onClick={() => save()}>Save</Button>待处理
从 onClick 返回一个 Promise,让按钮保持待处理,直到它结束。等待期间,按钮保持焦点,并忽略后续的按压。
<Button
onClick={() => new Promise((resolve) => setTimeout(resolve, 1500))}
pendingAnnouncement="Saving"
>
Save
</Button>一秒之后,它会向屏幕阅读器播报“Loading”。像上面那样设置 pendingAnnouncement 可以换掉这条消息,或者使用空字符串让它静默。
import { Button } from "@ui-sdk/solid/button"
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
function Example() {
return (
<Button onClick={() => wait(1500)} pendingAnnouncement="Saving">
Save
</Button>
)
}
export { Example }待处理内容
要在按钮等待时改变它显示的内容,用 data-show="idle" 或 data-show="pending" 标记内容,再用各自一条 CSS 规则在另一状态下隐藏它,或者使用 Tailwind 的 in-data-pending 变体:
[data-slot="button"]:not([data-pending]) [data-show="pending"],
[data-slot="button"][data-pending] [data-show="idle"] {
display: none;
}import { Button } from "@ui-sdk/solid/button"
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
function Example() {
return (
<Button onClick={() => wait(1500)} pendingAnnouncement="Saving">
<svg
data-show="idle"
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 17V3" />
<path d="m6 11 6 6 6-6" />
<path d="M19 21H5" />
</svg>
<svg
data-show="pending"
data-slot="spinner"
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
Save
</Button>
)
}
export { Example }保持标签不变,只改视觉,就像上面这样。如果文字也必须变,用同样的方式替换,不要加 aria-label。待处理的按钮解释了原因:
<Button onClick={save}>
<span data-show="idle">Save</span>
<span data-show="pending">Saving…</span>
</Button>处理错误
如果处理函数抛出异常或它的 Promise 被拒绝,state.error 会保存这个错误。用它来显示消息或重试标签。下一次按压会清除错误,并再次运行处理函数。
示例使用渲染函数在按钮旁边显示错误。
import { Button } from "@ui-sdk/solid/button"
import { useLog } from "./log"
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
function Example() {
const log = useLog()
return (
<div data-slot="stack">
<Button
onClick={async () => {
await wait(1000)
log("Couldn't save. Check your connection and try again.")
throw new Error("Couldn't save")
}}
render={(props, state) => (
<button {...props}>
{state.pending
? "Saving…"
: state.error
? "Try Again"
: "Save Changes"}
</button>
)}
/>
</div>
)
}
export { Example }await 之后的变更
onClick 会收到事件和 { source },后者说明按钮是如何被按压的。如果处理函数在 await 之后更改另一个 ui-sdk 组件,就用 withSource 包住那次变更,以保留原来的来源。否则,之后的变更会被上报为 "programmatic"。
这里 save() 是你的请求,status 是一个 Input 的控制器:
import { Button } from "@ui-sdk/solid/button"
import { withSource } from "@ui-sdk/solid/observe"
function SaveButton() {
return (
<Button
onClick={async (event, { source }) => {
await save()
withSource(source, () => status.setValue("Saved"))
}}
>
Save
</Button>
)
}
export { SaveButton }观察解释了来源跟踪。保留 "agent" 能让 undoSource("agent") 把之后的那次变更也包含进去。
禁用
设置 disabled 来阻止按压,并把按钮从 Tab 顺序中移除。按钮外层禁用的 <fieldset> 也会禁用它。
<Button disabled>Disabled</Button>import { Button } from "@ui-sdk/solid/button"
function Example() {
return <Button disabled>Disabled</Button>
}
export { Example }禁用时仍可聚焦
如果人们仍应能聚焦禁用的按钮,就加上 focusableWhenDisabled。它使用 aria-disabled,而不是原生的 disabled 属性。按压仍然不起作用。
用 aria-describedby 说明这个动作为什么不可用:
<Button disabled focusableWhenDisabled aria-describedby="publish-hint">
Publish
</Button>
<p id="publish-hint">Add a title to publish.</p>import { createSignal, createUniqueId } from "solid-js"
import { Button } from "@ui-sdk/solid/button"
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import { Input } from "@ui-sdk/solid/input"
import { useLog } from "./log"
function Example() {
const log = useLog()
const [title, setTitle] = createSignal("")
const hint = createUniqueId()
const ready = () => title().trim() !== ""
return (
<div data-slot="stack">
<Field>
<FieldLabel>Title</FieldLabel>
<Input value={title()} onValueChange={(value) => setTitle(value)} />
</Field>
<div data-slot="row">
<Button
disabled={!ready()}
focusableWhenDisabled
aria-describedby={hint}
onClick={() => log(`Published “${title()}”`)}
>
Publish
</Button>
<p id={hint} data-slot="hint">
{ready() ? "Ready to publish." : "Add a title to publish."}
</p>
</div>
</div>
)
}
export { Example }链接
用一个 render 函数,把提供的 props 展开到一个 <a> 上。它会保留 href 和链接语义,包括在新标签页中打开。禁用的链接无法导航,并且会离开 Tab 顺序。
<Button render={(props) => <a {...props} href="/docs/solid" />}>
Get started
</Button>import { Button } from "@ui-sdk/solid/button"
function Example() {
return (
<div data-slot="row">
<Button render={(props) => <a {...props} href="#installation" />}>
Get Started
</Button>
<Button disabled render={(props) => <a {...props} href="#changelog" />}>
Changelog
</Button>
</div>
)
}
export { Example }要使用你自己的组件,见部件与组合。
表单
设置 type="submit" 来提交表单,或 type="reset" 来恢复表单的默认值。默认的 type="button" 两者都不做。
<Button type="submit">Subscribe</Button>
<Button type="reset">Reset</Button>import { Button } from "@ui-sdk/solid/button"
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import { Input } from "@ui-sdk/solid/input"
import { useLog } from "./log"
function Example() {
const log = useLog()
return (
<form
data-slot="stack"
onSubmit={(event) => {
event.preventDefault()
const email = String(new FormData(event.currentTarget).get("email"))
log(`Subscribed ${email}`)
}}
>
<Field>
<FieldLabel>Email</FieldLabel>
<Input name="email" type="email" defaultValue="ada@example.com" />
</Field>
<div data-slot="row">
<Button type="submit">Subscribe</Button>
<Button type="reset">Reset</Button>
</div>
</form>
)
}
export { Example }Button 跟踪的是它自己的 onClick 返回的 Promise,而不是表单提交处理函数返回的那个。对于异步提交处理函数,自己维护一个待处理标志,并在它运行时给按钮设置 disabled,同时用 focusableWhenDisabled 让按钮在等待时保持焦点。
样式
用 data-pending 显示加载指示器或等待光标,用 data-disabled 为不可用的动作设置样式。按钮的 data-slot 是 button,它的属性列在数据属性下。
样式与动画涵盖了所有组件共用的样式模式。
数据属性
Button
[data-slot="button"]
| 属性 | 含义 |
|---|---|
data-pending | Present while the Promise its press handler returned is running. |
data-disabled | Present when disabled. |
API 参考
Button 接受原生按钮的 props 和下面的选项。render、children、class 和 style 可以读取按钮的状态;在 JSX 里读取状态,让它保持响应式。见部件与组合。
Button
disabled?boolean- Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless
focusableWhenDisabledis set. focusableWhenDisabled?boolean- Keeps a disabled button in the tab order with
aria-disabledinstead of the native attribute, so it can hold focus while it becomes disabled and host a tooltip that says why. Presses still do nothing. type?"button" | "reset" | "submit"- What a native button does in a form:
"submit"submits it and"reset"resets it. Ignored when the button renders as something else. pendingAnnouncement?string- What screen readers hear once the button has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.
debug?boolean- Logs every state change with its reason to the console, in development builds.
状态
disabledboolean- Whether it's disabled, by the
disabledoption or a disabled fieldset around it. A running press shows inpendinginstead. pendingboolean- Whether the Promise the last press returned is still running. Presses do nothing meanwhile.
errorunknown- Why the last press failed: what its handler threw, or its Promise rejected with. Cleared by the next press.
事件
Solid 的绑定写法 onClick={[handler, data]} 会调用 handler(data, event, { source })。
| Prop | 收到 |
|---|---|
onClick | 原生点击事件和 { source },即按钮是如何被按压的。返回一个 Promise 会让它保持待处理,直到它结束。 |
无障碍
给按钮一个清晰的文本标签。如果它只包含一个图标,加上 aria-label。原生按钮响应 Enter 和 Space;链接响应 Enter。
待处理的按钮
动作运行期间,按钮会告诉辅助技术它正忙,所以你不需要添加任何东西:
- 它设置
aria-busy="true"和aria-disabled="true",并在动作结束前忽略按压。整个过程它一直保持焦点。 - 一秒之后,它通过一个礼貌的实时区域(polite live region)播报
pendingAnnouncement(默认是"Loading")。快速的动作保持静默。这是一条状态消息:人们不用移动焦点就能听到。
要显示进度,保持标签不变,只改视觉,比如一个加载指示器。改变文字会在按钮获得焦点时给它改名:屏幕阅读器并不能可靠地播报聚焦元素上的新名称,所以这种改动主要帮助有视力的用户,而且文字长度变化时按钮的宽度也会跟着变。播报已经告诉大家它正在工作。
<Button onClick={save} pendingAnnouncement="Saving">
<ArrowDownToLineIcon data-show="idle" aria-hidden="true" />
<LoaderCircleIcon data-show="pending" aria-hidden="true" />
Save
</Button><Button onClick={save} aria-label="Save">
{saving() ? "Saving…" : "Save"}
<span aria-live="polite">{saving() ? "Saving" : ""}</span>
</Button>第二个按钮自己跟踪 saving,显示的文字不在它的无障碍名称里,并且把同一个状态播报了两次。如果文字无论如何都必须变,就用 data-show 替换它,并去掉 aria-label,这样按钮的名称始终包含屏幕上的文字。标记见待处理内容。
参考:
经过测试的行为
以下行为由自动化测试覆盖:
- Clicking a button runs its handler.
- Space presses a focused button.
- Enter presses a focused button.
- A submit button submits its form.
- A reset button resets its form.
- A disabled button can't be focused or pressed.
- A button rendered as a link stays a link.
- It stays focusable and says it's disabled.
- Tab reaches it.
- Clicking it runs nothing and submits nothing.
- Space on it runs nothing and submits nothing.
- Enter on it runs nothing and submits nothing.
- A returned Promise makes it busy, and it keeps focus until the Promise settles.
- While pending, it says it's unavailable with aria-disabled and keeps focus.
- Still pending after a second, it tells screen readers it's loading.
- A rejected Promise ends the pending state.
运行于 React、Vue 和 web components。