4 个版本 (2 个重大更改)
0.2.0 | 2023年2月15日 |
---|---|
0.1.0 | 2022年8月23日 |
0.0.2 | 2022年1月8日 |
0.0.1 | 2021年2月19日 |
#434 在 WebAssembly
每月189 次下载
48KB
447 代码行
Observable-react
所以,您想使用 wasm_bindgen 将 Rust 添加到现有的 React 应用中,或者您还没有准备好使用 Rust Web 框架?
有许多示例演示了 WASM 用于计算密集型工作负载,但如何将其连接到 React 组件渲染呢?
此 crate 包装 observable-rs,提供与 React 绑定的 wasm_bindgen 兼容性
示例用法
import React, { useMemo, useReducer } from "react";
import { useObserve } from "observable-rs";
function App({ wasm }: { wasm: any }) {
let [listVisible, toggleShow] = useReducer((show: boolean) => { return !show }, true);
let [thing, the_list] = useMemo(() => {
let thing = wasm.create_rust_thing();
setInterval(() => thing.do_something(), 1000);
return [thing, thing.get_the_list()];
}, [wasm]);
return (
<div className="App">
<button onClick={toggleShow}>{listVisible ? "Hide the list" : "Show the List"} </button><br />
{ listVisible ? <TheList the_list={the_list} /> : ''}
</div>
);
}
export default App;
function TheList({ the_list }: { the_list: any }) {
// Bind this observable to the react component
useObserve(the_list);
return (
<div>The List:<br />
<ul>
{the_list.map((v: any) => (
<li key={v}>{v}</li>
))}
</ul>
</div>
)
}
示例设置
首先,按照这里提供的设置说明创建一个包含捆绑 Rust crate 的 React 应用
https://dev.to/lokesh007/webassembly-with-rust-and-react-using-create-react-app-67
注意
- 建议在创建 React 应用时使用 TypeScript 标志:
npx create-react-app your_react_app --template typescript
- 将 .config-overrides.json 中的
extraArgs: "--no-typescript"
更改为extraArgs: ""
- 您的 wasm 构建输出目录(在 config-overrides.json 中指定)必须位于或符号链接到您的 React 应用 src 目录中,以便进行捆绑
然后
cd your_react_app
# This adds the useObserve() helper function to your react app
npm i observable-rs
# Your rust crate for application logic, to be compiled to WASM
cd your_wasm_crate_dir
# Add this crate
cargo add observable-react
cd your_react_app
npm serve
有关工作示例,请参阅 示例 React 应用
注意:由于 wasm_bindgen 目前无法捆绑 JavaScript 辅助函数,您必须在 React 应用中安装以下 npm 包 observable-rs
依赖项
~1.9–4MB
~68K SLoC