我正在尝试服务器端 blazor。我正在尝试使用多个按钮设置/更改在剃刀组件的标签中播放的 .mp4 文件。我发现实现这项工作的唯一方法是通过 IJSRuntime:InvokeVoidAsync() 从我的 razor 组件中的 OnParametersSet() 调用 javascript 函数。 javascript 函数位于_Host.cshtml 中。对于一个本应简单的问题来说,这似乎是一个相当丑陋的解决方案。
我尝试在 OnClick 按钮函数中使用 StateHasChanged() 。当我查看 chrome 中的 html 渲染时,h1-header 标记和源 src="NewFile" 显示更新,并且单击按钮时 h1 标记在页面上正确更改,但未加载新视频。我的猜测是,这与在自己的线程上播放的视频有关,或者视频标签本身没有改变。我只是不明白如何从 razor/c# 完成此操作。
由于构建错误,Javascript 代码已添加到文件:_Html.cshtml
<script>
function loadVideo (strNewVideo)
{
document.getElementById('videoSourceId').src = strNewVideo;
document.getElementById("videoTagId").load();
}
</script>
播放视频的简单组件...
文件:VideoPlayer.razor
@inject IJSRuntime theJavaScriptEngine;
<div class="align-content-center">
<h1>@this.m_strRenderMe</h1>
<video id="videoTagId" autoplay width="1080" height="720">
<source id="videoSourceId" [email protected] /cdn-cgi/l/email-protection_strRenderMe type="video/mp4" />
</video>
</div>
@code {
ElementReference theVideoTag;
[Parameter]
public string strVideoFilePath { get; set; }
private string m_strRenderMe;
protected override void OnParametersSet()
{
this.m_strRenderMe = this.strVideoFilePath;
theJavaScriptEngine.InvokeVoidAsync("loadVideo", this.m_strRenderMe);
this.StateHasChanged();
}
}
Razor 页面包含上面的组件和 4 个按钮
文件:Counter.razor
@page "/counter"
@using UseBlazorToReadPowerPoint.Classes
@inject CPersistantAppState thePersistantAppState
<VideoPlayer [email protected] /cdn-cgi/l/email-protection_strVideoPath></VideoPlayer>
<button class="btn btn-primary" @onclick="PlayVideo_1">Video 1</button>
<button class="btn btn-primary" @onclick="PlayVideo_2">Video 2</button>
<button class="btn btn-primary" @onclick="PlayVideo_3">Video 3</button>
<button class="btn btn-primary" @onclick="PlayVideo_4">Video 4</button>
@code {
void PlayVideo_1()
{
thePersistantAppState.m_strVideoPath = "videos/Video-1.mp4";
}
void PlayVideo_2()
{
thePersistantAppState.m_strVideoPath = "videos/Video-2.mp4";
}
void PlayVideo_3()
{
thePersistantAppState.m_strVideoPath = "videos/Video-3.mp4";
}
void PlayVideo_4()
{
thePersistantAppState.m_strVideoPath = "videos/Video-4.mp4";
}
}
保留所选的文件名。
文件:CPersistantAppState.cs
namespace UseBlazorToReadPowerPoint.Classes
{
public class CPersistantAppState
{
public string m_strVideoPath;
}
}
列出的代码有效。我只是不知道如何在没有 javascript 调用的情况下完成这项工作。似乎必须有一种更清洁的方法来做到这一点。