首页 > 解决方案 > 在 clojurescript 中,如何评估列表

问题描述

假设有

(def defining-list `(def one 1))

如何评估定义列表以使一个变为 1 ?(在clojurescript中)

编辑:我将给出更广泛的形象以及我在这里试图完成的工作以避免陷入 X/y 问题。

我正在尝试使用 cljsjs 包中的 cljsjs/material-ui 而不是每次都定义一个反应组件来使用它,如下所示:

(def app-bar 
  (r/adapt-react-class (aget js/MaterialUI (name :AppBar)))

我想从一组标签中定义所有组件:

(def material-ui-tags '[AppBar Avatar Backdrop])

所以我在想是否可以在不使用宏的情况下做到这一点,因为我发现了这个

就像是:

(doseq [component material-ui-tags]
  `(def ~(symbol (->kebab-case component)) (r/adapt-react-class (aget js/MaterialUI ~(name component)))))

但上面确实只创建了一个 defs 列表,我想评估这些。在 clojure 中, eval 可以解决问题。

标签: reactjsmaterial-uiclojurescript

解决方案


使用试剂,您可以使用https://github.com/reagent-project/reagent/blob/master/docs/InteropWithReact.md中记录的:>简写adapt-react-class

此外,您可以使用点表示法,js/我认为在 1.9.854 以上的 shadow-cljs 或 cljs 中,您可以require导入符号而不是使用aget.

在你的情况下,它会是这样的:

(ns example.core
  (:require [MaterialUI]))

(defn component-two []
  [:> MaterialUI/AppBar {:some-prop "some-value"}
    [:div "children-here"]])

(defn component-two []
  ;; If the require above doesn't work
  [:> js/MaterialUI.AppBar {:some-prop "some-value"}
    [:div "children-here"]])

要使用 def 执行您想要的操作,您需要 eval 或宏。正如 Jared Smith 在评论中解释的那样,Eval 并不理想。

您从 reagent-material-ui 链接的示例使用宏。调用宏实际上执行扩展然后评估。所以你的代码需要是这样的:

clj 文件

(def material-ui-tags '[AppBar Avatar Backdrop])

(defmacro adapt-components []
  (for [component material-ui-tags]
    `(def ~(symbol (->kebab-case component)) (reagent.core/adapt-react-class (aget js/MaterialUI ~(name component))))))

.cljs 文件

(adapt-components) ;; your defs will be available below this line

(defn my-component []
  [app-bar ...])

推荐阅读