How can I use Clojurescript to interact with the html DOM?

£可爱£侵袭症+ 提交于 2019-12-05 04:34:15

ClojureScript provides good interoperability with JavaScript and the browser. You can call JavaScript globals and functions directly to query and manipulate DOM like so:

(-> js/document
    (.getElementById "app")
    (.-innerHTML)) ; returns contents of element with id 'app'

(-> js/document
    (.getElementById "app")
    (.-innerHTML)
    (set! "Hello Clojure!")) ; Sets new content for element

Checkout ClojureScript cheatsheet for short summary of JavaScript inter-operability in CLJS.

However, modern Web apps are not built with such direct DOM manipulation. @scott-lowe's answer suggests using Reagent, which is a ClojureScript bridge for React, (one of) the most popular JS framework for UIs at the moment. A good choice for getting started with Web apps.

In addition, I would recommend looking at re-frame, which builds on Reagent, and provides state management for your app. Easy way to get started is to install the Leiningen build tool, and simply say lein new re-frame my-app-name. This gives you a good template to start experimenting. Run the app with lein figwheel and you can see your changes to the cljs code instantly in the browser. A good place to start hacking is views.cljs, which contains hiccup-like template for your main app.

Take a look at the Reagent project, which "provides a minimalistic interface between ClojureScript and React".

The Reagent project website includes this example:

(ns example
  (:require [reagent.core :as r]))

(defn simple-component []
  [:div
   [:p "I am a component!"]
   [:p.someclass
    "I have " [:strong "bold"]
    [:span {:style {:color "red"}} " and red "] "text."]])

(defn render-simple []
  (r/render [simple-component]
    (.-body js/document)))

In the above example, the Reagent component simple-component is rendered into the DOM at the body node of js/document. The Reagent component is just a simple function, but you can compose more complex blocks of HTML by composing these simple functions together.

There are many other ways to generate HTML and interact with the DOM from ClojureScript, but I think it's fair to say that Reagent is one of the most popular libraries in the ClojureScript community right now; it's also mature and well documented.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!