rust - 如何在 Dioxus 中添加全局 keydown 事件监听器)?

标签 rust webassembly dioxus

我目前正在尝试dioxus对于 Rust,我正在尝试找出如何处理全局键盘按下事件。

我想使用箭头键来回移动图像:

这是我到目前为止的代码:

use dioxus::{events::*, prelude::*};
use log::{info, LevelFilter};

/**
 * Specify <link data-trunk rel="copy-dir" href="src/assets" />
 * in the index.html to copy the files!!
 *
 * You'll see them in the dist directory!
 */

fn main() {
    dioxus_logger::init(LevelFilter::Info).expect("failed to init logger");
    dioxus::web::launch(app);
}

fn app(cx: Scope) -> Element {
    let mut index = use_state(&cx, || 1);

    let change_evt = move |evt: KeyboardEvent| match evt.key.as_str() {
        "ArrowRight" => index += 1,
        "ArrowLeft" => index -= 1,
        _ => {}
    };

    let url = format!("/assets/img/wallpaper/1042/0{}.jpg", index);
    cx.render(rsx!(img {
        src: "{url}",
        onkeydown: change_evt,
    }))
}

在 JavaScript 中会是这样的

document.addEventListener('keydown', (evt) => {
 // Do magic
}

我尝试遵循calculator example但无法让它工作。

有什么想法吗?

最佳答案

这就是我最终在 Yew 所做的事情。

我使用了 wasm_bindgen 和 web_sys。这可能对 Dioxus 有用

use wasm_bindgen::{prelude::Closure, JsCast, UnwrapThrowExt};
use web_sys::window;

    use_effect(move || {
        let callback = Closure::wrap(Box::new(move |e: web_sys::KeyboardEvent| {
            let key = e.key();
            let key_str = key.as_str();
            match key_str {
                "ArrowLeft" => {
                  // Do something here
                }
                "ArrowRight" => {
                  // Do something here
                }
                _ => {}
            }
        }) as Box<dyn FnMut(_)>);

        win.add_event_listener_with_callback("keydown", callback.as_ref().unchecked_ref())
            .unwrap();

        move || {
            win.remove_event_listener_with_callback("keydown", callback.as_ref().unchecked_ref())
                .unwrap();
        }
    });

这是cargo.toml的一部分

[dependencies]
web-sys = { version = "0.3.60", features = ['console'] }
wasm-bindgen = { version = "0.2.83" }

关于rust - 如何在 Dioxus 中添加全局 keydown 事件监听器)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74833748/

相关文章:

rust - 我怎样才能创建一个接受任何类型的函数?

java - Android NDK : Two prebuilt shared libraries, 但其中一个依赖于另一个

rust - 如何更改 Rust 中 &Path 的第一个祖先?

rust - 无法返回对lazy_static HashMap中元素的引用,因为它的生存时间不够长

emscripten - 使用 Emscripten 编译的 WebAssembly 可以生成更小的文件大小吗

javascript - 在 Rust web 程序集中访问 UInt8ClampedArray

webassembly - 理解类结构和构造函数调用