多租户 Next.js + Tailwind 应用程序:如何动态更改主题?

问题描述 投票:0回答:2

我目前正在开发一个多租户 Next.js + Tailwind 应用程序,租户应该能够动态更改样式/主题。

我似乎无法解决这个挑战,在我看来,每次更改样式时都需要重建 next.js 应用程序,但是是否有可能以某种方式更改一个租户的样式而不重建应用程序?

我想要实现的目标:租户更新样式参数,从而更新数据库。当租户网络应用程序重新加载时,新样式会立即应用,没有任何延迟和重建。

typescript next.js multi-tenant
2个回答
0
投票

使用React的

Context
来渲染样式,即。亮/暗模式

或者。

使用状态管理库/浏览器的localStorage来设置样式并更改Tailwind中html组件的类


0
投票

我通过结合查看 URL 和向客户端发送服务器道具来实现我的工作。

例如,我让后端发送一些样式,例如

primaryColor

工作示例如下:

  1. 在渲染代码之前的 page.tsx 中。您可以从 URL 中获取tenantId。然后您使用该 ID 从后端检索样式。
async function getSearchParams() {
  const headersInstance = headers();
  const pathname = headersInstance.get("referer");
  if (!pathname) return new URLSearchParams();

  const urlSearchParams = new URLSearchParams(pathname.split("?")[1]);
  return urlSearchParams;
}

async function getTenantId() {
  const searchParams = await getSearchParams();
  const tenantId = searchParams.get("tenantId");

  if (tenantId) {
    return tenantId;
  }
  return "";
}

async function getStyles(tenantId: string) {
  try {
    const response = await fetch(`http://localhost:3000/themes/${tenantId}`);
    return response.json();
  } catch (error) {
    return {};
  }
}
  1. 在服务器组件中调用这些数据并将它们发送到客户端组件
export default async function Main(){
  const tenantId = await getTenantId();
  const styles = await getStyles(tenantId);

  return (
    <div>
      <ClientComponent styles={styles} />
    </div>
  )
}
  1. 在您的客户端组件中,动态设置全局 CSS 变量
const ClientComponent = ({styles}) => {
  useEffect(() => {
    document.documentElement.style.setProperty("--primary-color", primaryColor);
  }, [primaryColor]);

return (
<div className="bg-primary w-100 h-100">
my colour is changed
</div>
© www.soinside.com 2019 - 2024. All rights reserved.