I am new to Clojurescript. I want to know how to create html elements, and how to change their properties using clojurescript. I cannot seem to find a lot of relevant information online.
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.
来源:https://stackoverflow.com/questions/45228474/how-can-i-use-clojurescript-to-interact-with-the-html-dom