如何在Yew Rust中从状态(state)获取值

huangapple go评论65阅读模式
英文:

How to get the value from state in Yew Rust

问题

我在 Yew 中有一个状态,看起来像这样:

let is_flipped: UseStateHandle<bool> = use_state(|| false);

如你所见,它的类型是 `UseStateHandle&lt;bool&gt;`。

我想要提取其中的布尔值,以便可以切换状态:

let onclick: Callback<MouseEvent> = {
let is_flipped = is_flipped.clone();
Callback::from(move |_| match is_flipped {
true => is_flipped.set(false), // <- 类型错误
false => is_flipped.set(true), // <- 类型错误
})
};


但是我得到了这个错误:

^^^^^ 期望结构体 UseStateHandle,找到 bool


我怎样才能获得状态中包含的布尔值呢?
英文:

I have a state in Yew that looks like this:

let is_flipped: UseStateHandle&lt;bool&gt; = use_state(|| false);

As you can see, its type is UseStateHandle&lt;bool&gt;.

I want to extract its boolean value so I can toggle the state:

let onclick: Callback&lt;MouseEvent&gt; = {
    let is_flipped = is_flipped.clone();
    Callback::from(move |_| match is_flipped {
        true =&gt; is_flipped.set(false), // &lt;- type error
        false =&gt; is_flipped.set(true), // &lt;- type error
    })
};

But I am getting this error:

^^^^^ expected struct `UseStateHandle`, found `bool`

How can I obtain the boolean value contained in the state?

答案1

得分: 4

UseStateHandle实现了Deref。你只需要对它进行解引用:

let onclick: Callback<MouseEvent> = {
    let is_flipped = is_flipped.clone();
    Callback::from(move |_| match *is_flipped {
        true => is_flipped.set(false),
        false => is_flipped.set(true),
    })
};
英文:

UseStateHandle implements Deref. You just need to dereference it:

let onclick: Callback&lt;MouseEvent&gt; = {
    let is_flipped = is_flipped.clone();
    Callback::from(move |_| match *is_flipped {
        true =&gt; is_flipped.set(false),
        false =&gt; is_flipped.set(true),
    })
};

huangapple
  • 本文由 发表于 2023年2月23日 21:02:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定