我目前正在开发一个多租户 Next.js + Tailwind 应用程序,租户应该能够动态更改样式/主题。
我似乎无法解决这个挑战,在我看来,每次更改样式时都需要重建 next.js 应用程序,但是是否有可能以某种方式更改一个租户的样式而不重建应用程序?
我想要实现的目标:租户更新样式参数,从而更新数据库。当租户网络应用程序重新加载时,新样式会立即应用,没有任何延迟和重建。
使用React的
Context
来渲染样式,即。亮/暗模式
或者。
使用状态管理库/浏览器的localStorage来设置样式并更改Tailwind中html组件的类
我通过结合查看 URL 和向客户端发送服务器道具来实现我的工作。
例如,我让后端发送一些样式,例如
primaryColor
。
工作示例如下:
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 {};
}
}
export default async function Main(){
const tenantId = await getTenantId();
const styles = await getStyles(tenantId);
return (
<div>
<ClientComponent styles={styles} />
</div>
)
}
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>