티스토리 뷰
Rust 코드로 작성하는 WASM (with react)
Document getElementById method
javascript의 Dom method 중 getElementById를 wasm으로 구현할 수 있습니다.
web_sys::Document의 get_element_by_id(id) 메서드를 이용할 수 있습니다.
cargo.toml 설정
[dependencies.js-sys]
version = "0.3.5"
[dependencies.web-sys]
version = "0.3.5"
features = [
'console',
'Document',
'Window',
'HtmlElement',
]
web_sys에서 지원하는 window.document.get_element_by_id('id')를 사용하면 id와 일치하는 document를 잡고 console.log를 이용하여 출력합니다.
rust 코드
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
pub fn document_get_element_by_id(id: String) {
let window = web_sys::window().expect("No window");
let document = window.document().expect("No document");
let val = document.get_element_by_id(&id)
.unwrap()
.dyn_into::<web_sys::HtmlElement>()
.unwrap();
web_sys::console::log_2(&"Find Document: %s".into(), &JsValue::from_str(&val.inner_text()));
}
react 코드
function DocumentContainer() {
useEffect(() => {
const getWindow = import('../../../wasm-rust/pkg');
getWindow
.then(module => {
module.get_window('id');
}).catch(e => {
console.log(e);
});
}, []);
return (
<div id='id'>
</div>
);
}
react에서 반환하는 JSX.Element의 div에 id값을 'id'로 설정합니다.
wasm의 함수에 id값을 parameter로 넘겨주어 해당 id에 맞는 dom을 찾으면 console창에 출력할 것입니다.
create element, append child
html element를 생성하고 삽입할 수 있습니다.
rust 코드
use wasm_bindgen::JsCast;
fn get_window() -> web_sys::Window {
let window = web_sys::window().expect("global window dose not exist");
window
}
fn get_document(window: web_sys::Window) -> web_sys::Document {
let document = window.document().expect("expecting a document on window");
document
}
pub fn document_get_element_by_id(id: String) -> web_sys::HtmlElement {
let window = get_window();
let document = get_document(window);
let node = document.get_element_by_id(&id)
.unwrap()
.dyn_into::<web_sys::HtmlElement>()
.unwrap();
node
}
pub fn document_create_element(id: String) {
let window = get_window();
let document = get_document(window);
let _parent = document_get_element_by_id(id);
//html 요소를 string형태로 생성
let tmp = "
<div>
create div tag
</div>
<span>
create span tag
</span>
";
//html div요소 생성
let div_ele = document.create_element("div").unwrap();
// create_element로 생성한 div요소에 string으로 생성한 요소를 삽입
div_ele.set_inner_html(tmp);
_parent.append_child(&div_ele).unwrap();
}
여기서 두가지 방법으로 요소를 생성하였습니다.
web_sys::Document의 create_element 메서드를 이용한 방법, string을 이용한 방법,
둘다 javascript로 구현이 가능한 형태입니다.
javascript에서는 Document.createElement 메서드를 이용하여 요소를 생성할 수 있고, string형태로도 요소를 생성하여 다른 요소에 삽입할 수 있습니다.
react 코드
function DocumentContainer() {
useEffect(() => {
const getWindow = import('../../../wasm-rust/pkg');
getWindow
.then(module => {
module.create_element('create-element');
}).catch(e => {
console.log(e);
});
}, []);
return (
<div id='create-element'>
</div>
);
}
wasm은 id가 create-element인 요소를 찾고 해당 요소 내부에 새로 생성한 요소를 삽입할것 입니다.
querySelector
query selector 기능도 지원합니다.
rust 코드
pub fn document_query_selector(id: String) {
let window = get_window();
let document = get_document(window);
// query_selector에 넘겨줄 string form 생성
let mut query = String::from("#");
query.push_str(&id);
// id를 이용한 query selector 메서드 실행
let node = document.query_selector(&query)
.unwrap()
.unwrap()
.dyn_into::<web_sys::HtmlElement>()
.unwrap();
// 선택된 노드에 문자열 삽입
let tmp = "set string from query-selector";
node.set_inner_text(&tmp);
}
web_sys::Document의 query_selector 메서드를 이용하였고, set_inner_text 메서드를 이용하여 문자열을 삽입했습니다.
react 코드
function DocumentContainer() {
useEffect(() => {
const getWindow = import('../../../wasm-rust/pkg');
getWindow
.then(module => {
module.qeury_selector('query-selector');
}).catch(e => {
console.log(e);
});
}, []);
return (
<div id='query-selector'>
</div>
);
}
rust wasm 문서 - web_sys
https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Document.html
Document in web_sys - Rust
The type that holds the reference to Self for the duration of the invocation of the function that has an &Self parameter. This is required to ensure that the lifetimes don’t persist beyond one function call, and so that they remain anonymous. Read more
rustwasm.github.io
'front-end > wasm' 카테고리의 다른 글
Rust코드로 작성하는 WASM(feat. react) (3) event_listener (0) | 2021.08.30 |
---|---|
Rust 코드로 작성하는 WASM(feat. react) (1) console.log (0) | 2021.08.16 |
react에 rust webassembly 프로젝트 연결하기 (0) | 2021.07.30 |
[WASM] Web Assembly with Rust 생성 및 실행해보기 (0) | 2021.03.29 |