てぃぐれのプログラマwiki

ワクワクに従う

Blazorでjsを呼び出してclassを追加【C#/Blazor】

経緯

前回の続きで、jsっぽいことをblazorでやるんだが、

あえてjsを呼び出して、blazorの意味ねーっていうことをしてみた。

 

コード

js

window.jsFunctions = {
    test: function (xxx) {

        const x = document.getElementById(xxx);
        x.classList.add('table');
    },
}

 

razor

<table id="tb">
    <thead>
        <tr>
            <th>Date</th>
            <th>Temp. (C)</th>
            <th>Temp. (F)</th>
            <th>Summary</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var forecast in forecasts)
        {
            <tr>
                <td>@forecast.Date.ToShortDateString()</td>
                <td>@forecast.TemperatureC</td>
                <td>@forecast.TemperatureF</td>
                <td>@forecast.Summary</td>
            </tr>
        }
    </tbody>
</table>


@code {
    private WeatherForecast? forecasts;
   
    protected override async Task OnInitializedAsync()
    {
        forecasts = await Http.GetFromJsonAsync<WeatherForecast>("WeatherForecast");
       
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await JSRuntime.InvokeVoidAsync("jsFunctions.test","tb");
    }
}

 

意味ないけど、きっといつか意味ある日が来ると思うし、逆にjsを使っちゃって中途半端になりそうやなあー。