如何用blazor和bootstrap实现深色主题?

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

https://docs.blazorbootstrap.com/ 上,Github 和 Twitter 链接附近有一个明暗主题切换器:Light and dark theme switcher on blazorbootstrap site

但是没有解释如何做到这一点。如果您将 data-bs-theme="dark" 属性应用于

<html>
元素https://getbootstrap.com/docs/5.3/customize/color-modes/#enable-dark-,Bootstrap 5 现在支持深色主题模式

我尝试使用 javascript 函数使其在 blazor 中工作,这些函数读取选定的主题并将其写入本地存储:

function setTheme(theme) {
    localStorage.setItem('theme', theme);
    // set data-bs-theme to the body element
    document.documentElement.setAttribute('data-bs-theme', theme);
}

function getTheme() {
    console.log("Getting theme: " + localStorage.getItem('theme'));
    return localStorage.getItem('theme');
}

(function() {
    let theme = localStorage.getItem('theme');
    if (theme == null) {
        setTheme('light');
    } else {
        setTheme(theme);
    }
})();

我还有我的主题切换组件,它使用 IJSRuntime 来触发主题更改:

@rendermode InteractiveAuto
@inject IJSRuntime Js
<div class="nav-item px-3">
    @if(_theme == "dark")
    {
        <a class="nav-link" @onclick='() => SetTheme("light")'>
            <Icon Class="px-3" Name=IconName.Moon />Light theme
        </a>
    }
    else
    {
        <a class="nav-link" @onclick='() => SetTheme("dark")'>
            <Icon Class="px-3" Name=IconName.Sun />Dark theme
        </a>
    }
</div>

@code {
    private string _theme = "";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        _theme = await Js.InvokeAsync<string>("getTheme");
    }

    private Task SetTheme(string theme)
    {
        Js.InvokeVoidAsync("setTheme", theme);
        _theme = theme;
        return Task.CompletedTask;
    }
}

这一直有效,直到我尝试转到不同的页面。然后 html 元素被覆盖,我的

data-bs-theme
属性消失了,一切都变成了浅色主题。然而,当我刷新页面时,由于 javascript 立即调用了函数,一切都会再次变为深色主题。

如何正确实施?

blazor darkmode blazor-bootstrap
1个回答
0
投票

私有无效暗模式() { _当前主题 = _isDarkMode ? ApplicationTheme.DefaultTheme : ApplicationTheme.DarkTheme; _isDarkMode = !_isDarkMode; }

© www.soinside.com 2019 - 2024. All rights reserved.