rust 有没有办法把一个 prop 传给戴奥瑟斯的主要组件?

insrf1ej  于 2023-03-02  发布在  其他
关注(0)|答案(1)|浏览(168)

我最近开始用dixus编写用户界面,有一个很大的结构体要传递给不同的组件。我不能完全控制这个结构体,因为它来自第三方库。这个结构体不能是const,因此不能是全局的。它必须在main中初始化。一个简化的示例可能如下所示:

use dioxus::prelude::*;

#[derive(Props)]
struct BigStructWrapper<'a> {
    s: &'a mut BigStruct,
}

#[allow(non_snake_case)]
fn App<'a>(cx: Scope<'a, BigStructWrapper<'a>>) -> Element {
    cx.render(rsx! {
        div {
            // Something with BigStructWrapper/BigStruct
        }
    })
}

fn main() {
    let big_struct = BigStructWrapper {
        s: &mut BigStruct::new(),
    };

    dioxus_desktop::launch(App);
}

然后我得到错误:

error[E0308]: mismatched types
  --> src/main.rs:40:28
   |
31 |     dioxus_desktop::launch(App);
   |     ---------------------- ^^^ expected fn pointer, found fn item
   |     |
   |     arguments to this function are incorrect
   |
   = note: expected fn pointer `for<'a> fn(&'a Scoped<'a>) -> Option<VNode<'a>>`
                 found fn item `for<'a> fn(&'a Scoped<'a, BigStructWrapper<'a>>) -> Option<VNode<'a>> {

是否有变通方法允许这样做?是否有更合适的方法在不使用 Package 器结构的情况下完成此操作?

6yt4nkrj

6yt4nkrj1#

我想你要找的东西在dixus文档的Sharing State部分已经描述过了。你可以用use_stateuse_ref这样的函数来处理dixus中的状态。下面是一个关于use_state的小例子,我们在App中创建BigStruct示例,并将其传递给其他组件:

#![allow(non_snake_case)]

use dioxus::prelude::*;

#[derive(Debug, PartialEq)]
struct BigStruct;

impl BigStruct {
    fn new() -> Self {
        Self
    }
}

fn App(cx: Scope) -> Element {
    let big_struct = use_state(cx, || BigStruct::new());

    cx.render(rsx! {
        Element { bs: big_struct }
    })
}

#[inline_props]
fn Element<'a>(cx: Scope, bs: &'a BigStruct) -> Element {
    cx.render(rsx! {
      div {
        "hello {bs:?}"
      }
    })
}

fn main() {
    dioxus_desktop::launch(App);
}

相关问题