Rust UI框架Dioxus核心库dioxus-core-types的使用,高效构建跨平台Web与桌面应用

Rust UI框架Dioxus核心库dioxus-core-types的使用,高效构建跨平台Web与桌面应用

安装

在项目目录中运行以下Cargo命令:

cargo add dioxus-core-types

或者在Cargo.toml中添加以下行:

dioxus-core-types = "0.6.2"

核心功能

dioxus-core-types是Dioxus UI框架的核心类型库,它提供了构建跨平台应用所需的基础类型和功能。Dioxus是一个使用Rust编写的声明式UI框架,可以高效地构建Web和桌面应用程序。

示例代码

下面是一个完整的Dioxus应用示例,展示了如何使用dioxus-core-types构建跨平台UI:

use dioxus::prelude::*;

fn main() {
    // 启动应用
    dioxus::desktop::launch(App);
}

// 定义应用组件
fn App(cx: Scope) -> Element {
    // 使用状态钩子
    let mut count = use_state(&cx, || 0);

    // 构建UI
    cx.render(rsx! {
        div {
            h1 { "Hello Dioxus!" }
            p { "Count: {count}" }
            button {
                onclick: move |_| count += 1,
                "Click me"
            }
        }
    })
}

完整示例demo

以下是一个更完整的Dioxus应用示例,包含多个组件和交互:

use dioxus::prelude::*;

fn main() {
    // 启动桌面应用
    dioxus::desktop::launch(App);
}

// 主应用组件
fn App(cx: Scope) -> Element {
    // 使用状态管理
    let mut todos = use_state(&cx, || Vec::<String>::new());
    let mut input_text = use_state(&cx, || String::new());

    cx.render(rsx! {
        div {
            h1 { "Todo App with Dioxus" }
            
            // 输入表单
            form {
                onsubmit: move |event| {
                    event.prevent_default();
                    if !input_text.is_empty() {
                        todos.make_mut().push(input_text.get().clone());
                        input_text.set(String::new());
                    }
                },
                input {
                    r#type: "text",
                    value: "{input_text}",
                    oninput: move |e| input_text.set(e.value.clone()),
                    placeholder: "输入待办事项"
                }
                button { "添加" }
            }
            
            // 待办事项列表
            ul {
                for (i, todo) in todos.iter().enumerate() {
                    li {
                        key: "{i}",
                        "{todo} "
                        button {
                            onclick: move |_| {
                                todos.make_mut().remove(i);
                            },
                            "删除"
                        }
                    }
                }
            }
            
            // 子组件
            TodoCount { count: todos.len() }
        }
    })
}

// 子组件 - 显示待办事项数量
#[inline_props]
fn TodoCount(cx: Scope, count: usize) -> Element {
    cx.render(rsx! {
        div {
            style: "margin-top: 20px; color: gray;",
            "待办事项总数: {count}"
        }
    })
}

跨平台特性

上述代码可以通过简单的配置编译为:

  • Web应用 (使用dioxus-web)
  • 桌面应用 (使用dioxus-desktop)
  • 移动应用 (使用dioxus-mobile)

核心类型

dioxus-core-types提供了以下核心功能:

  • 虚拟DOM类型
  • 组件生命周期管理
  • 属性系统
  • 事件系统
  • 状态管理

许可证

MIT OR Apache-2.0


1 回复

Rust UI框架Dioxus核心库dioxus-core-types使用指南

Dioxus是一个高性能的Rust UI框架,可以用于构建跨平台的Web和桌面应用。dioxus-core-types是Dioxus的核心类型库,提供了构建UI所需的基础类型和特性。

核心概念

1. Component trait

所有Dioxus组件都需要实现Component trait:

use dioxus_core_types::Component;

struct MyComponent;

impl Component for MyComponent {
    type Props = ();

    fn render(&self, cx: Scope<Self::Props>) -> Element {
        cx.render(rsx! {
            div { "Hello, Dioxus!" }
        })
    }
}

2. Scope

Scope是组件渲染的上下文,提供了访问props、状态管理和创建元素的能力:

fn render(cx: Scope) -> Element {
    let count = use_state(&cx, || 0);
    
    cx.render(rsx! {
        button { onclick: move |_| count.set(count + 1), 
            "Count: {count}" 
        }
    })
}

3. Element

Element是Dioxus中的基本渲染单元,可以通过rsx!宏创建:

let element: Element = rsx! {
    div {
        class: "container",
        h1 { "Welcome to Dioxus" },
        p { "Building UIs with Rust is fun!" }
    }
};

主要类型

1. Props

组件属性通过泛型参数定义:

#[derive(Props)]
struct UserProps {
    name: String,
    age: u32,
}

impl Component for UserProfile {
    type Props = UserProps;
    
    fn render(&self, cx: Scope<UserProps>) -> Element {
        cx.render(rsx! {
            div {
                h2 { "User Profile" },
                p { "Name: {cx.props.name}" },
                p { "Age: {cx.props.age}" }
            }
        })
    }
}

2. Event handlers

事件处理是响应式UI的核心:

rsx! {
    button {
        onclick: move |event| {
            println!("Button clicked! Event: {:?}", event);
        },
        "Click me"
    }
}

3. State management

状态管理通过hooks实现:

fn Counter(cx: Scope) -> Element {
    let count = use_state(&cx, || 0);
    
    cx.render(rsx! {
        div {
            button { onclick: move |_| count.set(count() - 1), "-" }
            span { "{count}" }
            button { onclick: move |_| count.set(count() + 1), "+" }
        }
    })
}

高级用法

1. 动态子元素

fn DynamicChildren(cx: Scope) -> Element {
    let items = use_state(&cx, || vec!["Item 1", "Item 2", "Item 3"]);
    
    cx.render(rsx! {
        ul {
            items.iter().map(|item| rsx! {
                li { key: "{item}", "{item}" }
            })
        }
    })
}

2. 条件渲染

fn ConditionalRender(cx: Scope) -> Element {
    let show = use_state(&cx, || true);
    
    cx.render(rsx! {
        div {
            button { onclick: move |_| show.set(!show), "Toggle" },
            if *show.get() {
                rsx! { p { "This is visible" } }
            } else {
                None
            }
        }
    })
}

3. 生命周期管理

impl Component for LifecycleDemo {
    type Props = ();
    
    fn render(&self, cx: Scope<()>) -> Element {
        use_effect(&cx, (), |_| async move {
            println!("Component mounted");
            
            || println!("Component unmounted")
        });
        
        cx.render(rsx! { div { "Lifecycle Demo" } })
    }
}

跨平台注意事项

Dioxus支持Web和桌面平台,但需要注意:

  1. 事件处理在不同平台可能有细微差异
  2. 某些Web特定的API在桌面端不可用
  3. 样式系统在不同平台上的表现可能不同

完整示例Demo

下面是一个结合了状态管理、事件处理和条件渲染的完整Dioxus应用示例:

use dioxus::prelude::*;

fn main() {
    // 启动Dioxus应用
    dioxus::desktop::launch(App);
}

// 定义主应用组件
fn App(cx: Scope) -> Element {
    // 使用状态hook管理计数器
    let count = use_state(&cx, || 0);
    
    // 使用状态hook管理显示/隐藏状态
    let show_message = use_state(&cx, || true);

    // 渲染UI
    cx.render(rsx! {
        div {
            class: "app-container",
            
            h1 { "Dioxus 示例应用" }
            
            // 计数器部分
            div {
                class: "counter-section",
                
                button {
                    onclick: move |_| count.set(count() - 1),
                    "减少"
                }
                
                span { "当前计数: {count}" }
                
                button {
                    onclick: move |_| count.set(count() + 1),
                    "增加"
                }
            }
            
            // 切换显示消息的按钮
            button {
                onclick: move |_| show_message.set(!show_message),
                if *show_message.get() { "隐藏消息" } else { "显示消息" }
            }
            
            // 条件渲染的消息
            (*show_message.get()).then(|| rsx! {
                p { "这是一个动态显示/隐藏的消息" }
            })
            
            // 动态列表渲染
            ul {
                (1..=5).map(|i| rsx! {
                    li { key: "{i}", "列表项 {i}" }
                })
            }
        }
    })
}

总结

dioxus-core-types提供了构建Dioxus应用所需的核心类型和特性。通过组合这些基础元素,可以构建复杂的跨平台UI应用。核心概念包括:

  • 组件(Component)作为UI构建块
  • 作用域(Scope)提供渲染上下文
  • 元素(Element)作为渲染单元
  • 属性(Props)用于组件配置
  • 状态管理通过Hooks实现

Dioxus的响应式模型和Rust的类型系统相结合,可以构建高效且类型安全的UI应用。

回到顶部