1个不稳定版本
0.1.1 | 2023年3月15日 |
---|---|
0.1.0 |
|
#109 in #yew
8KB
Yew html attributes
Yew html attributes是一个宏crate,允许您轻松将标准HTML属性添加到您的组件中,并将它们传递给子组件。
用法
要将HTML属性添加到您的props中,只需在props之前添加#[has_html_attributes]
并在HasHtmlAttributes
中派生。
然后使用带有子html元素引用和props引用的use_attributes!
宏来传递它们。
use yew::prelude::*;
use yew_attributes_macro::prelude::*;
#[has_html_attributes]
#[derive(Debug, Clone, PartialEq, Default, Properties, HasHtmlAttributes)]
pub struct InputProps{}
#[function_component(Input)]
pub fn input(props:&InputProps) -> Html {
let node_ref = use_node_ref();
use_attributes!(node_ref, props);
html! {
<>
<input ref={node_ref} type="text" />
</>
}
}
元素参数
默认情况下,宏只为所有html元素添加公共属性。如果您想使元素接收所有关联属性,请在has_html_attributes
中提供element
参数。
use yew::prelude::*;
use yew_attributes_macro::prelude::*;
#[has_html_attributes(element=input)]
#[derive(Debug, Clone, PartialEq, Default, Properties, HasHtmlAttributes)]
pub struct InputProps{}
#[function_component(Input)]
pub fn input(props:&InputProps) -> Html {
let node_ref = use_node_ref();
use_attributes!(node_ref, props);
html! {
<>
<input ref={node_ref} type="text" />
</>
}
}
排除参数
您可能想要删除一些属性以避免覆盖组件内部的一些逻辑。为此,您必须将exclude
参数添加到has_html_attributes
中,并列出您想要排除的所有属性。
use yew::prelude::*;
use yew_attributes_macro::prelude::*;
#[has_html_attributes(exclude="oninput,onclick")]
#[derive(Debug, Clone, PartialEq, Default, Properties, HasHtmlAt Finished dev [unoptimized + debuginfo] target(s) in 1.76stributes)]
pub struct InputProps{}
#[function_component(Input)]
pub fn input(props:&InputProps) -> Html {
let node_ref = use_node_ref();
use_attributes!(node_ref, props);
html! {
<>
<input ref={node_ref} type="text" />
</>
}
}
不可见参数
默认情况下,宏为所有可见的html元素添加公共属性。如果您只想有所有html元素的公共属性,请使用不可见参数。
use yew::prelude::*;
use yew_attributes_macro::prelude::*;
#[has_html_attributes(invisible=false)]
#[derive(Debug, Clone, PartialEq, Default, Properties, HasHtmlAttributes)]
pub struct ScriptProps{}
#[function_component(Script)]
pub fn script(props:&ScriptProps) -> Html {
let node_ref = use_node_ref();
use_attributes!(node_ref, props);
html! {
<>
<script ref={node_ref} />
</>
}
}
依赖
~19MB
~336K SLoC