如何让 Stripe Elements 使用 Next-themes 动态改变样式

How to get Stripe Elements to dynamically change styles with Next-themes

我正在使用条纹元素并根据主题动态更改输入样式。它有效,但我唯一的问题是,如果我在包含条纹元素输入的页面上更改主题,我必须硬刷新页面才能看到 CSS 更改。

我想要实现的是当主题改变时让样式改变。请注意,我正在尝试更改背景颜色。

这是我目前拥有的:

import { useTheme } from "next-themes";

 const { resolvedTheme, setTheme } = useTheme();

  const CARD_OPTIONS = {
    iconStyle: "solid",
    style: {
      base: {
        backgroundColor: `${resolvedTheme === "dark" ? "black" : "white"}`,
        iconColor: "#6D28D9",
        color: `${resolvedTheme === "dark" ? "white" : "#9CA3AF"}`,
        fontWeight: "500",
        fontFamily: "Roboto, Open Sans, Segoe UI, sans-serif",
        fontSize: "16px",
        fontSmoothing: "antialiased",
        ":-webkit-autofill": {
          color: "#fce883",
        },
        "::placeholder": {
          color: "#D1D5DB",
        },
      },
      invalid: {
        iconColor: "#ef2961",
        color: "#ef2961",
      },
    },
  };

<CardElement options={CARD_OPTIONS} />

我尝试过的另一个选项是使用挂载,然后将 DARK_CARD_OPTIONS 传递给卡片元素。

像这样:

const [mounted, setMounted] = useState(false);

useEffect(() => setMounted(true), []);

 const DARK_CARD_OPTIONS = {
    iconStyle: "solid",
    style: {
      base: {
        backgroundColor: "red",
        iconColor: "#6D28D9",
        color: "white,
        fontWeight: "500",
        fontFamily: "Roboto, Open Sans, Segoe UI, sans-serif",
        fontSize: "16px",
        fontSmoothing: "antialiased",
        ":-webkit-autofill": {
          color: "#fce883",
        },
        "::placeholder": {
          color: "#D1D5DB",
        },
      },
      invalid: {
        iconColor: "#ef2961",
        color: "#ef2961",
      },
    },
  };

  {mounted && (
          <div className="p-4 rounded-lg border border-gray-800 dark:border-gray-600 focus:border-purple-700">
            {resolvedTheme === "dark" ? (
              <CardElement options={DARK_CARD_OPTIONS} />
            ) : (
              <CardElement options={CARD_OPTIONS} />
            )}
          </div>
        )}

出于某种原因,这只会使 CardElements 输入的某些区域动态变化。

请看下面的截图(请注意我用红色来突出它):

当主题更改时,您必须强制重新安装 CardElement 才能使其正常工作:

<CardElement key={resolvedTheme} options={CARD_OPTIONS} />