我正在使用 Rust 构建一个简单的网络应用程序,并尝试在网站上显示图像。但我无法添加该图像。
我将 Rust 与名为Yew的框架和工具Trunk一起使用。
索引.html
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Yew Development</title>
<link data-trunk="" rel="scss" href="main.scss"> <!-- Successfull linked to this file -->
</head>
<body></body>
</html>
Run Code Online (Sandbox Code Playgroud)
.scss 文件成功完成其工作。
但是如何使用宏显示带有 Rust 文件的图像呢html!
?
主程序.rs
use yew::prelude::*;
fn main() {
yew::start_app::<App>();
}
#[function_component(App)]
fn app() -> Html {
html! {
<>
<h1> {"Hello world!"}</h1>
<link data-trunk="true" rel="copy-file" href="img/rust.png"/> // doesn't work …
Run Code Online (Sandbox Code Playgroud) 我正在研究 Rust 并查看 Yew 框架(Rust 的前端框架)的这些简单说明: https: //yew.rs/docs/tutorial。
\n我按照说明进行操作,直到收到命令
\ntrunk serve --open\n
Run Code Online (Sandbox Code Playgroud)\n然而,某处出现故障。
\n这就是我得到的:
\ntrunk serve --open\n
Run Code Online (Sandbox Code Playgroud)\n这是我的 Cargo.toml 文件:
\n2022-05-06T19:07:54.087214Z INFO starting build\n2022-05-06T19:07:54.087870Z INFO spawning asset pipelines\n2022-05-06T19:07:54.168329Z INFO building yew-app\n Finished dev [unoptimized + debuginfo] target(s) in 0.01s\n2022-05-06T19:07:54.232154Z INFO fetching cargo artifacts\n2022-05-06T19:07:54.295124Z INFO processing WASM for yew-app\n2022-05-06T19:07:54.301974Z INFO downloading wasm-bindgen version="0.2.80"\n2022-05-06T19:07:54.302269Z ERROR \xe2\x9d\x8c error\nerror from HTML pipeline\n\nCaused by:\n 0: error from asset pipeline\n 1: failed downloading release archive\n 2: unsupported architecture\n2022-05-06T19:07:54.302531Z …
Run Code Online (Sandbox Code Playgroud) 这个问题是为 Yew v0.19 编写的
异步外部 JavaScript 函数可以通过Closures在 Rust 中使用,作为传入的函数:
#[wasm_bindgen]
extern "C" {
fn setInterval(closure: &Closure<dyn FnMut()>, time: u32) -> i32;
}
// ...
let cb = Closure::new(|| {
log("interval elapsed!");
});
let interval_id = setInterval(&cb, 1_000);
Run Code Online (Sandbox Code Playgroud)
这对于迂腐的例子来说很好,但是Closure
有一个关键的要求 - 所应用的函数需要有一个'static
生命周期。同样,对于 Yew 应用程序,自发响应的完美机制是枚举Message
,并将其update()
命名为Model
. 然而,(发出消息的)link()
机制没有静态生命周期。Context
在理想的情况下,提交给闭包的值可以仅作为 Yew 组件消息应用:
struct Model {
thing: Option<JsValue>,
}
enum Msg {
GotThing(JsValue),
}
#[wasm_bindgen]
extern "C" {
fn createThing(closure: &Closure<dyn …
Run Code Online (Sandbox Code Playgroud) 通常在 Rust 应用程序中,我会使用 获得系统时间std::time::SystemTime::now()
,但这在 yew 应用程序中似乎不起作用。相反,我试图以静默方式(从服务器日志)读取系统时间的组件失败,并且在 Web 控制台中我得到panicked at 'time not implemented on this platform'
.
这是有道理的,出于安全原因,客户端应用程序不能随意从操作系统中获取系统时间。但是 yew 是否提供了一种从浏览器获取此信息的方法?
每当我运行trunk build
或cargo run --target=wasm32-unknown-unknown
遇到一堆范围错误时。
我已经运行了rustup target add wasm32-unknown-unknown
和cargo install --locked wasm-bindgen-cli
,但仍然没有运气。
这些错误消息是什么意思?
\n[编辑]\n输出很长,但它是这样开始的:
\n[2m2022-06-06T01:51:52.351114Z[0m [32m INFO[0m starting build\n[2m2022-06-06T01:51:52.351741Z[0m [32m INFO[0m spawning asset pipelines\n[2m2022-06-06T01:51:52.390738Z[0m [32m INFO[0m building yew-app\n Compiling ryu v1.0.10\n Compiling itoa v1.0.2\n Compiling cfg-if v1.0.0\n Compiling hashbrown v0.11.2\n Compiling slab v0.4.6\n Compiling scoped-tls-hkt v0.1.2\n Compiling serde v1.0.137\n Compiling thiserror v1.0.31\nerror[E0463]: can\'t find crate for `core`\n |\n = note: the `wasm32-unknown-unknown` target may not be installed\n = …
Run Code Online (Sandbox Code Playgroud) 我有一个 yew 结构组件,它应该向 api 发出 get 请求,然后呈现项目列表。我正在尝试在组件的 render 方法内执行请求,但遇到了生命周期问题,无法在 wasm_bindgen_future 中使用对 self 的引用。我必须使用 wasm_bindgen_future 才能执行异步 api 请求。这是代码(大致)
pub struct ViewLessonPlans {
lesson_plans: Vec<LessonPlan>,
loading_condition: ComponentLoadingStage
}
impl Component for ViewLessonPlans {
type Message = ();
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
Self {
lesson_plans: vec![],
loading_condition: ComponentLoadingStage::Loading
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
match self.loading_condition {
ComponentLoadingStage::Loading => {
html! { <h1>{"Lesson Plans Loading"}</h1>}
},
ComponentLoadingStage::Success => {
self.lesson_plans.iter().map(|lp| {
html! { <ViewLessonPlan …
Run Code Online (Sandbox Code Playgroud) 我尝试按照https://dev.to/arctic_hen7/how-to-set-up-tailwind-css-with-yew-and-trunk-il9中描述的步骤在 Yew 中使用 Tailwind CSS,但是它不起作用。
我的测试项目文件夹:
货物.toml:
[package]
name = "yew-tailwind-app"
version = "0.1.0"
edition = "2021"
[dependencies]
yew = { version = "0.19" }
Run Code Online (Sandbox Code Playgroud)
索引.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link data-trunk href="./tailwind.css" rel="css" />
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
main.rs中的代码:
use yew::prelude::*;
#[function_component(App)]
fn app() -> Html {
html! {
<>
<h1>{ "Hello World" }</h1>
<p class={ classes!("bg-red-500") }>{"Test!"}</p>
</>
}
}
fn main() {
yew::start_app::<App>();
}
Run Code Online (Sandbox Code Playgroud)
但我在“测试!”中没有看到红色背景颜色。你能帮我吗?
我只是想通过我的一个孩子的 props 将一个函数传递给他们,以便在那里使用它。
这是我现在的代码
use log::info;
use yew::html::onclick::Event;
use yew::prelude::*;
// Create Properties with the function I want to use
#[derive(yew::Properties, PartialEq)]
pub struct MyProps {
pub do_this: fn(Event) -> (),
pub val: String,
}
#[function_component(Base)]
pub fn home(props: &MyProps) -> Html {
let do_this_func = props.do_this.clone();
html! {
<button onclick={move |e: Event| do_this_func(e)}> {"press me"} </button>
}
}
// Pass the function
#[function_component(App)]
pub fn app() -> Html {
fn do_this_func(s: Event) {
info!("clicked from my func")
}
html! …
Run Code Online (Sandbox Code Playgroud) 运行docker build -t <IMAGE_NAME> .
然后运行docker run -p 8080:8080 <IMAGE_NAME>
日志到控制台,它可以工作,但 127.0.0.1:8080 不显示客户端
Dockerfile:
FROM rust:1.60.0-slim-buster
WORKDIR /app
COPY . .
RUN rustup target add wasm32-unknown-unknown
RUN cargo install --locked --version 0.15.0 trunk
RUN trunk build --release
EXPOSE 8080
CMD ["trunk", "serve", "--release"]
Run Code Online (Sandbox Code Playgroud)
Cargo.toml
[package]
name = "yew-whos-that-pokemon-client"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
getrandom = { version = "0.2.4", features = ["js"] }
rand = "0.8.5"
reqwest …
Run Code Online (Sandbox Code Playgroud) 有什么办法可以通过 DOM 操作吗use_node_ref
?或者,如何document.query_selector()
使用红豆杉在 Rust 中进行操作?
use web_sys::HtmlInputElement;
use yew::{
function_component, functional::*, html,
NodeRef, Html
};
#[function_component(UseRef)]
pub fn ref_hook() -> Html {
let input_ref = use_node_ref();
let all_editables = input_ref.query_selector("[contenteditable]")
web_sys::console::(all_editables)
html! {
<div>
<input ref={input_ref} type="number" />
</div>
}
}
Run Code Online (Sandbox Code Playgroud)
目标:我有一个富文本编辑器应用程序。我有一个像这样的字符串形式的缩小的 html <h1> this is title</h1><p>hello world</>
,我需要获取 DOM 并更改innerHTML
以将其设置为此值。
目标2:innerHtml
当用户在元素中写入内容时,我还需要更新contenteditable
。例如,当用户输入时@john smith
,我将创建一个<a>
元素,其中包含指向 的个人资料的href
链接。John smith
如何在 WebAssembly 中使用 web-sys 创建带有 JSON 主体的 POST 请求?
下面这个例子展示了如何发出 GET 请求,我需要更改opts.method("GET"); 到opts.method("POST"); 但我如何将 JSON 主体传递给 reqeuest.
let mut opts = RequestInit::new();
opts.method("GET");
opts.credentials(web_sys::RequestCredentials::Include);
let request = Request::new_with_str_and_init(
"http://localhost:8080/api/v1/books",
&opts
).unwrap();
match web_sys::window() {
Some(window) => {
let _res = JsFuture::from(window.fetch_with_request(&request))
.await
.map(|err| web_sys::console::log_1(&format!("{:?}", err)
.into()));
},
None => web_sys::console::log_1(&format!("window is none").into()),
}
Run Code Online (Sandbox Code Playgroud) 我遇到了 Yew 库的组件机制的问题。如果我在主模型的 html 宏的宏中包含任何其他 html 代码,编译器会抱怨“只允许一个根 html 元素”。
我的结构如下:
主程序.rs
impl Component for Model {
// ...
fn view(&self) -> Html<Self> {
html! {
<Navigation />
<p>{ "Hello World!" }</p>
}
}
}
Run Code Online (Sandbox Code Playgroud)
组件/navigation.rs
impl Component for Navigation {
// ...
fn view(&self) -> Html<Self> {
html! {
<nav class=("uk-navbar-container","uk-padding","uk-padding-remove-bottom","uk-padding-remove-top"), uk-navbar="">
// ...
</nav>
}
}
}
Run Code Online (Sandbox Code Playgroud)
我怀疑 html 宏在 html 标签周围添加了 -tag 或整个 index.html,从而导致“双”html 标签。但是,我怎样才能避免这种情况,或者在使用组件时我错过了什么?
rust ×12
yew ×12
trunk-rs ×4
wasm-bindgen ×3
webassembly ×3
web-sys ×2
callback ×1
closures ×1
components ×1
containers ×1
docker ×1
html ×1
lifetime ×1
reactjs ×1
rust-cargo ×1
tailwind-css ×1