[英]How do I Apply chaining method on javascript document.createElement
[英]How to do document.createElement in ReScript
ReScript 似乎是編寫 JS 代碼的更好方法,但我無法找到應該是簡單的單行文檔的內容。
如何調用document.createElement()
之類的函數?
我通過查看此頁面嘗試了 Js.document、Dom.document: https://rescript-lang.org/docs/manual/latest/api ,但該代碼在操場上出現錯誤:
Js中找不到有價
document
在 Dom 中找不到有價document
要調用 JS 函數,您需要使用 ReScript 的JS interop 。 在這種情況下,您可以使用external
關鍵字和@val
/ @scope
屬性來獲取一個 ReScript function,它會在調用時調用document.createElement
:
@val @scope(("window", "document"))
external createElement: string => unit = "createElement"
createElement("div")
這將轉換為
window.document.createElement('div');
對於快速原型制作,您也可以只使用external
對象並直接與 RS 對象等對象交互:
@val external document: 'a = "document"
document["createElement"]("div")
查看interop 備忘單和external
文檔以了解更常見的模式。
你可以使用 bs-webapi
open Webapi.Dom
open Belt
document
->Document.asHtmlDocument
->Option.flatMap(document => document->HtmlDocument.body)
->Option.map(body => {
let root = document->Document.createElement("div", _)
root->Element.setId("app")
root->Element.appendChild(body)
})
->ignore
由於 re-script 由 React (JSX) 提供支持,而不是標准的 ECMA JavaScript,我認為您不能使用像document.createElement
這樣的調用。
相反,您應該通過以下方式創建元素:
let element = <h1> {React.string("Hello World")} </h1>
這轉換為以下內容:
var element = React.createElement("h1", undefined, "Hello World");
我修改了默認的 Playground 腳本:
module Button = {
@react.component
let make = (~count: int) => {
let times = switch count {
| 1 => "once"
| 2 => "twice"
| n => Belt.Int.toString(n) ++ " times"
}
let msg = "Click me " ++ times
let element = <button> {React.string(msg)} </button>
element
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.