【问题标题】:How to get Stripe Elements to dynamically change styles with Next-themes如何让 Stripe Elements 使用 Next-themes 动态更改样式
【发布时间】:2022-01-22 11:37:26
【问题描述】:

我正在使用条纹元素并根据主题动态更改输入样式。它可以工作,但我唯一的问题是,如果我在包含条纹元素输入的页面上更改主题,我必须硬刷新页面才能看到 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} />

我尝试过的另一个选项是使用 mount,然后将 DARK_CARD_OPTIONS 传递给 Card Element。

像这样:

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 输入的某些区域动态变化。

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

【问题讨论】:

    标签: css reactjs next.js stripe-payments


    【解决方案1】:

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

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

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2018-02-12
    • 2017-10-13
    • 1970-01-01
    • 2014-04-13
    • 2018-09-27
    • 1970-01-01
    • 2020-02-01
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多