ReScript似乎是编写JS代码的更好方法,但我无法找到应该是简单的单行文档的方法。
如何调用像document.createElement()这样的函数
我尝试了Js.document,Dom.document,通过查看这个页面:https://rescript-lang.org/docs/manual/latest/api,但是该代码在操场上出现了一个错误:
在Js中找不到值
document在Dom中找不到document值
发布于 2021-05-20 18:18:55
要调用JS函数,您需要使用ReScript的JS互操作。在这种情况下,您可以使用external关键字和@val/@scope属性获得一个ReScript函数,在调用时调用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")发布于 2021-05-25 05:45:55
你可以使用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发布于 2021-05-20 18:04:29
因为JavaScript是由React (JSX)驱动的,而不是标准的ECMA JavaScript,我不认为您可以使用像document.createElement这样的调用。
相反,您应该通过以下方式进行创建元素:
let element = <h1> {React.string("Hello World")} </h1>这种情况转化为以下几点:
var element = React.createElement("h1", undefined, "Hello World");我修改了默认的游乐场脚本:
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
}
}https://stackoverflow.com/questions/67625468
复制相似问题