Заметка
Доступ к этой странице требует авторизации. Вы можете попробовать войти в систему или изменить каталог.
Доступ к этой странице требует авторизации. Вы можете попробовать сменить директорию.
Примечание.
Это не последняя версия этой статьи. В текущей версии см. версию .NET 10 этой статьи.
Предупреждение
Эта версия ASP.NET Core больше не поддерживается. Дополнительные сведения см. в политике поддержки .NET и .NET Core. В текущем выпуске см . версию .NET 9 этой статьи.
Компоненты могут записывать и отображать дополнительные атрибуты в дополнение к объявленным параметрам и полям компонента. Дополнительные атрибуты можно записать в словаре, а затем применить к элементу с именем splatting, когда компонент отрисовывается с помощью атрибута @attributesRazor директивы. Этот сценарий полезен при определении компонента, который создает элемент разметки, поддерживающий разнообразные настройки. Например, это может быть утомительным определять атрибуты отдельно для <input>, который поддерживает множество параметров или полей.
Сплетирование атрибутов
Следующий компонент Splat:
- Первый
<input>элемент (id="useIndividualParams") использует отдельные поля компонентов. - Второй элемент
<input>(id="useAttributesDict") использует сплаттинг атрибутов.
Splat.razor:
@page "/splat"
<PageTitle>SPLAT!</PageTitle>
<h1>Splat Parameters Example</h1>
<input id="useIndividualParams"
maxlength="@maxlength"
placeholder="@placeholder"
required="@required"
size="@size" />
<input id="useAttributesDict"
@attributes="InputAttributes" />
@code {
private string maxlength = "10";
private string placeholder = "Input placeholder text";
private string required = "required";
private string size = "50";
private Dictionary<string, object> InputAttributes { get; set; } =
new()
{
{ "maxlength", "10" },
{ "placeholder", "Input placeholder text" },
{ "required", "required" },
{ "size", "50" }
};
}
@page "/splat"
<PageTitle>SPLAT!</PageTitle>
<h1>Splat Parameters Example</h1>
<input id="useIndividualParams"
maxlength="@maxlength"
placeholder="@placeholder"
required="@required"
size="@size" />
<input id="useAttributesDict"
@attributes="InputAttributes" />
@code {
private string maxlength = "10";
private string placeholder = "Input placeholder text";
private string required = "required";
private string size = "50";
private Dictionary<string, object> InputAttributes { get; set; } =
new()
{
{ "maxlength", "10" },
{ "placeholder", "Input placeholder text" },
{ "required", "required" },
{ "size", "50" }
};
}
@page "/splat"
<input id="useIndividualParams"
maxlength="@maxlength"
placeholder="@placeholder"
required="@required"
size="@size" />
<input id="useAttributesDict"
@attributes="InputAttributes" />
@code {
private string maxlength = "10";
private string placeholder = "Input placeholder text";
private string required = "required";
private string size = "50";
private Dictionary<string, object> InputAttributes { get; set; } =
new()
{
{ "maxlength", "10" },
{ "placeholder", "Input placeholder text" },
{ "required", "required" },
{ "size", "50" }
};
}
@page "/splat"
<input id="useIndividualParams"
maxlength="@maxlength"
placeholder="@placeholder"
required="@required"
size="@size" />
<input id="useAttributesDict"
@attributes="InputAttributes" />
@code {
private string maxlength = "10";
private string placeholder = "Input placeholder text";
private string required = "required";
private string size = "50";
private Dictionary<string, object> InputAttributes { get; set; } =
new()
{
{ "maxlength", "10" },
{ "placeholder", "Input placeholder text" },
{ "required", "required" },
{ "size", "50" }
};
}
@page "/splat"
<input id="useIndividualParams"
maxlength="@maxlength"
placeholder="@placeholder"
required="@required"
size="@size" />
<input id="useAttributesDict"
@attributes="InputAttributes" />
@code {
private string maxlength = "10";
private string placeholder = "Input placeholder text";
private string required = "required";
private string size = "50";
private Dictionary<string, object> InputAttributes { get; set; } =
new()
{
{ "maxlength", "10" },
{ "placeholder", "Input placeholder text" },
{ "required", "required" },
{ "size", "50" }
};
}
@page "/splat"
<input id="useIndividualParams"
maxlength="@maxlength"
placeholder="@placeholder"
required="@required"
size="@size" />
<input id="useAttributesDict"
@attributes="InputAttributes" />
@code {
private string maxlength = "10";
private string placeholder = "Input placeholder text";
private string required = "required";
private string size = "50";
private Dictionary<string, object> InputAttributes { get; set; } =
new Dictionary<string, object>()
{
{ "maxlength", "10" },
{ "placeholder", "Input placeholder text" },
{ "required", "required" },
{ "size", "50" }
};
}
Кроме того id, отображаемые <input> элементы на веб-странице имеют одинаковые атрибуты:
<input id="useIndividualParams"
maxlength="10"
placeholder="Input placeholder text"
required="required"
size="50">
<input id="useAttributesDict"
maxlength="10"
placeholder="Input placeholder text"
required="required"
size="50">
Хотя в предыдущем примере используются поля для первого <input> элемента (id="useIndividualParams"), то же поведение применяется при использовании параметров компонента.
Произвольные атрибуты
Чтобы принять произвольные атрибуты, определите параметр компонента с помощью свойства CaptureUnmatchedValues, имеющего значение true:
@code {
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object>? InputAttributes { get; set; }
}
Свойство CaptureUnmatchedValues в [Parameter] позволяет параметру соответствовать всем атрибутам, которые не соответствуют никакому другому параметру. Компонент может определять только один параметр с CaptureUnmatchedValues. Тип свойства, используемый с CaptureUnmatchedValues, должен быть назначаемым из Dictionary<string, object> с ключами строки. В этом сценарии также можно использовать IEnumerable<KeyValuePair<string, object>> или IReadOnlyDictionary<string, object>.
Расположение @attributes относительно положения атрибутов элемента имеет значение. При наложении @attributes на рендеренном элементе атрибуты обрабатываются справа налево (от последнего к первому), при этом первый атрибут становится приоритетным для всех общих атрибутов. Рассмотрим следующий пример родительского компонента, который использует дочерний компонент, где дочерний элемент задает атрибут "extra" и родительский компонент присваивает атрибут "extra" дочернему компоненту.
AttributeOrderChild1.razor:
<div @attributes="AdditionalAttributes" extra="5" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object>? AdditionalAttributes { get; set; }
}
<div @attributes="AdditionalAttributes" extra="5" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object>? AdditionalAttributes { get; set; }
}
<div @attributes="AdditionalAttributes" extra="5" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object>? AdditionalAttributes { get; set; }
}
<div @attributes="AdditionalAttributes" extra="5" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object>? AdditionalAttributes { get; set; }
}
<div @attributes="AdditionalAttributes" extra="5" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object> AdditionalAttributes { get; set; }
}
<div @attributes="AdditionalAttributes" extra="5" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object> AdditionalAttributes { get; set; }
}
AttributeOrder1.razor:
@page "/attribute-order-1"
<PageTitle>Attribute Order 1</PageTitle>
<h1>Attribute Order Example 1</h1>
<AttributeOrderChild1 extra="10" />
<p>
View the HTML markup in your browser to inspect the attributes on
the AttributeOrderChild1 component.
</p>
AttributeOrder1.razor:
@page "/attribute-order-1"
<PageTitle>Attribute Order 1</PageTitle>
<h1>Attribute Order Example 1</h1>
<AttributeOrderChild1 extra="10" />
<p>
View the HTML markup in your browser to inspect the attributes on
the AttributeOrderChild1 component.
</p>
AttributeOrderParent1.razor:
@page "/attribute-order-parent-1"
<AttributeOrderChild1 extra="10" />
AttributeOrderParent1.razor:
@page "/attribute-order-parent-1"
<AttributeOrderChild1 extra="10" />
AttributeOrderParent1.razor:
@page "/attribute-order-parent-1"
<AttributeOrderChild1 extra="10" />
AttributeOrderParent1.razor:
@page "/attribute-order-parent-1"
<AttributeOrderChild1 extra="10" />
Атрибут AttributeOrderChild1 компонента extra стоит справа от @attributes. Отрисованный компонент AttributeOrderParent1<div> содержит extra="5" при передаче через дополнительный атрибут, так как атрибуты обрабатываются справа налево (с последнего к первому), и первый атрибут имеет приоритет; это жёстко закодированный extra HTML-атрибут компонента extra.
<div extra="5" />
В следующем примере порядок extra и @attributes изменён на обратный в элементе <div> дочернего компонента. В этом сценарии отрисованный компонент AttributeOrderParent2 содержит <div>, когда он передается через дополнительный атрибут extra="10", так как первый обработанный атрибут "extra" — это HTML-атрибут extra, разворачиваемый из родительского компонента.
AttributeOrderChild2.razor:
<div extra="5" @attributes="AdditionalAttributes" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object>? AdditionalAttributes { get; set; }
}
<div extra="5" @attributes="AdditionalAttributes" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object>? AdditionalAttributes { get; set; }
}
<div extra="5" @attributes="AdditionalAttributes" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object>? AdditionalAttributes { get; set; }
}
<div extra="5" @attributes="AdditionalAttributes" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object>? AdditionalAttributes { get; set; }
}
<div extra="5" @attributes="AdditionalAttributes" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object> AdditionalAttributes { get; set; }
}
<div extra="5" @attributes="AdditionalAttributes" />
@code {
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object> AdditionalAttributes { get; set; }
}
AttributeOrder2.razor:
@page "/attribute-order-2"
<PageTitle>Attribute Order 2</PageTitle>
<h1>Attribute Order Example 2</h1>
<AttributeOrderChild2 extra="10" />
<p>
View the HTML markup in your browser to inspect the attributes on
the AttributeOrderChild2 component.
</p>
AttributeOrder2.razor:
@page "/attribute-order-2"
<PageTitle>Attribute Order 2</PageTitle>
<h1>Attribute Order Example 2</h1>
<AttributeOrderChild2 extra="10" />
<p>
View the HTML markup in your browser to inspect the attributes on
the AttributeOrderChild2 component.
</p>
AttributeOrderParent2.razor:
@page "/attribute-order-parent-2"
<AttributeOrderChild2 extra="10" />
AttributeOrderParent2.razor:
@page "/attribute-order-parent-2"
<AttributeOrderChild2 extra="10" />
AttributeOrderParent2.razor:
@page "/attribute-order-parent-2"
<AttributeOrderChild2 extra="10" />
AttributeOrderParent2.razor:
@page "/attribute-order-parent-2"
<AttributeOrderChild2 extra="10" />
В <div> на отрисованной веб-странице родительского компонента содержится extra="10":
<div extra="10" />