假设我有一个自定义的剃须刀组件,名为MyComponent。该组件继承自ComponentBase,假设它是数据网格控件的一个版本。我在网上找到的代码示例,使用此代码作为示例来配置一些行为:
// index.razor
<MyComponent EditSettings=@_editSettings SelectionSettings=@_selectionSettings>
...
</MyComponent>
@code {
EditSettings _editSettings;
SelectionSettings _selectionSettings;
// somewhere in some method
_editSettings = new EditSettings() { ... };
_selectionSettings = new SelectionSettings() { ... };
}
从技术上讲,EditSettings和SelectionSettings的存在是为了定义组件的行为。我想添加对开发人员的支持,以便在HTML中配置该组件的行为,而不是在c#代码中。看看我感兴趣的这个假设例子:
// index.razor
<MyComponent>
<EditSettings AllowEdit="..." EditMode="..." OnEditCompleted="..." />
<SelectionSettings SelectionMode="..." OnSelectionChange="..." />
...
</MyComponent>
据我所知,为了在剃刀的HTML代码中显示它们,它们需要从ComponentBase继承?这是正确的吗?
如何在MyComponent代码中捕获用户定义的代码?它们的存在是可选的,用户可以选择不定义它们并使用默认行为。
您可以通过使用CascadingValue
组件将Settings
对象级联到子组件来实现这一点。还要将event
添加到Settings
类中,以便当子组件更改设置时,父组件会收到通知。示例:
SettingsA.cs
:
public class SettingsA
{
private bool? _allowThis;
private bool? _allowThat;
public bool AllowThis
{
get => _allowThis ?? false;
set
{
_allowThis = value;
NotifyStateChanged();
}
}
public bool AllowThat
{
get => _allowThat ?? false;
set
{
_allowThat = value;
NotifyStateChanged();
}
}
public event Action? OnChange;
private void NotifyStateChanged() => OnChange?.Invoke();
}
MyComponentSettingsA.razor
:
@code {
[CascadingParameter]
private SettingsA? SettingsA { get; set; }
[Parameter]
public bool AllowThis { get; set; }
[Parameter]
public bool AllowThat { get; set; }
protected override void OnInitialized()
{
if (SettingsA != null)
{
SettingsA.AllowThis = AllowThis;
SettingsA.AllowThat = AllowThat;
}
}
}
MyComponent.razor
:
@implements IDisposable
<CascadingValue Value="_settingsA">
@if (ChildContent != null)
{
@ChildContent
}
</CascadingValue>
@if (_settingsA.AllowThis)
{
<p>This is allowed</p>
}
@if (_settingsA.AllowThat)
{
<p>That is allowed</p>
}
@code {
private SettingsA _settingsA = new SettingsA();
[Parameter]
public RenderFragment? ChildContent { get; set; }
protected override void OnInitialized()
{
_settingsA.OnChange += StateHasChanged;
}
public void Dispose()
{
_settingsA.OnChange -= StateHasChanged;
}
}
用法:
<MyComponent>
<MyComponentSettingsA AllowThis="true" AllowThat="true" />
</MyComponent>
BlazorFiddle