useSetting
HOOK

HOOKS & API / 配置读写

useSetting

读取并修改 deskpack.json 中声明的某一项用户配置(options),让用户无需右键打开编辑面板也能在桌面卡片上直接切换模式或调参,并与「编辑小组件」面板保持双向同步。

签名#

签名
function useSetting<T = any>(
  key: string,
  fallback: T
): [T, (next: T) => void]

参数#

keystring必填
deskpack.json 的 options 中声明的配置键名。不能以 appearance. 或 desktop. 开头。
fallbackT必填
当该键尚未在设置中取值时返回的兜底默认值。

返回值#

valueT数组第 0 项
当前配置项的生效值。
setValuefunction数组第 1 项
调用 setValue(next) 保存新值到实例配置;宿主自动按清单中的 type、choices、min / max 校验合法性,并立即同步到右键「编辑小组件」面板。

示例:卡片内直接切换展示模式#

搭配 deskpack.json 中声明的 mode(type: "choice", choices: ["compact", "detailed"])与 Segmented 控件,桌面点一下即可持久化切换:

TSX
import React, { Segmented, Spacer, Text, VStack, useSetting, useWidget } from "deskset-react";

export default function ModeSwitchWidget() {
  const { theme, t } = useWidget();
  const [mode, setMode] = useSetting<string>("mode", "compact");

  return (
    <VStack
      maxWidth={true}
      maxHeight={true}
      padding={16}
      spacing={10}
      background={theme.isPure ? "clear" : "theme.card"}
      cornerRadius={theme.isPure ? 0 : theme.corner}
      clip={!theme.isPure}
    >
      <Segmented
        value={mode}
        onChange={setMode}
        options={[
          { id: "compact", label: t("精简", "Compact") },
          { id: "detailed", label: t("详细", "Detailed") },
        ]}
      />
      <Spacer />
      <Text fontSize={14} color="theme.ink">
        {mode === "detailed"
          ? t("展示全部指标与历史趋势", "Showing full metrics & history")
          : t("仅展示核心数值", "Showing headline figure only")}
      </Text>
    </VStack>
  );
}

何时用 useSetting vs useStorage?#

  • useSetting:适合希望同时出现在右键「编辑小组件」表单中的偏好设置(例如目标值、城市名、主题色、视图模式)。
  • useStorage:适合纯运行态内部数据(例如待办列表数组、每日打卡历史、上次缓存结果),不需要暴露给配置表单。