组件系统
小于 1 分钟euvuirustwasmusage-introductioncomponent
函数组件
函数组件接受 VirtualNode 作为 props,从中提取属性和子节点:
use euv::*;
pub fn my_card(props: VirtualNode) -> VirtualNode {
let title: String = props.try_get_prop(&Attribute::Title).unwrap_or_default();
let children: Vec<VirtualNode> = props.get_children();
let children_node: VirtualNode = VirtualNode::Fragment(children);
rsx! {
div {
class: c_card()
h3 {
class: c_card_title()
title
}
children_node
}
}
}提取 Props
// 提取自定义字符串属性
let label: String = props
.try_get_prop(&Attribute::Other("label".to_string()))
.unwrap_or_else(|| "Button".to_string());
// 提取标准 HTML 属性
let placeholder: String = props.try_get_prop(&Attribute::Placeholder).unwrap_or_default();
let value: String = props.try_get_prop(&Attribute::Value).unwrap_or_default();
let title: String = props.try_get_prop(&Attribute::Title).unwrap_or_default();
// 提取事件处理器
let onclick: Option<NativeEventHandler> = props.try_get_event(&NativeEventName::Click);
// 提取回调属性(自定义名称)
let on_click: Option<NativeEventHandler> = props.try_get_callback("on_click");
// 提取子节点
let children: Vec<VirtualNode> = props.get_children();在 RSX 中使用组件
自定义标签名会自动匹配同名的函数组件:
rsx! {
my_card {
title: "Card Title"
p { "Card content" }
}
}组件嵌套
rsx! {
my_card {
title: "Nested Components"
primary_button {
my_badge {
color: "#7c3aed"
text: "Badge"
}
}
}
}提示
RSX 中的自定义标签名必须与函数组件名一致,框架通过名称匹配自动调用。