如何在 clojurescript 中自定义本机对象的打印功能

how to customise the print function for native objects in clojurescript

我想要自定义反应元素的显示方式,这是代码:

(require ["react" :as react])    

(defn react-element? [obj]
  (if-let [sym (aget obj "$$typeof")]
    (= js/Symbol
       (type sym))))

(extend-protocol IPrintWithWriter
  object
  (-pr-writer [obj writer _]
    (js/console.log "hello")
    (cond (react-element? obj)
          (write-all writer
                     (-> (js->clj obj)
                         (dissoc "$$typeof")
                         str))

          :else
          (write-all writer (str obj)))))

(react/createElement "h2" nil "Hello, World!")

我希望输出是

{:type "h2", :key nil, :ref nil, :props {:children "Hello, World!"}}}

但它仍然打印出正常的#js 元素:

#js {"$$typeof" Symbol(react.element), 
     :type "h2", :key nil, :ref nil, 
     :props #js {:children "Hello, World!"}, :_owner nil}

有没有办法自定义此行为?

根本原因是标准lib打印代码中,使用了implements?,没有使用satisfies?。这有效地将打印覆盖限制为非本机类型的内容。 (implements? 不适用于本机类型)。

这可能不是故意的,可以通过 https://dev.clojure.org/jira/browse/CLJS-2812

修复