Allow raw React classes to be used with [:> comp ...]

This commit is contained in:
Dan Holmsand 2015-10-06 14:27:44 +02:00
parent 533c05aaca
commit e6b32c6aee
3 changed files with 41 additions and 10 deletions

View File

@ -71,9 +71,9 @@
;;; Rendering
(defn reagent-class? [c]
(defn ^boolean reagent-class? [c]
(and (fn? c)
(some? (.' c :prototype.reagentRender))))
(some? (some-> c .-prototype (.' :reagentRender)))))
(defn do-render-sub [c]
(let [f (.' c :reagentRender)
@ -316,10 +316,11 @@
(defn fn-to-class [f]
(assert (ifn? f) (str "Expected a function, not " (pr-str f)))
(warn-unless (not (and (fn? f)
(some? (.' f :type))))
(some? (some-> f .-prototype (.' :render)))))
"Using native React classes directly in Hiccup forms "
"is not supported. Use create-element or "
"adapt-react-class instead: " (.' f :type)
"adapt-react-class instead: " (let [n (fun-name f)]
(if (empty? n) f n))
(comp-name))
(let [spec (meta f)
withrender (assoc spec :reagent-render f)

View File

@ -228,12 +228,12 @@
(declare as-element)
(defn native-element [parsed argv]
(defn native-element [parsed argv first]
(let [comp (.' parsed :name)]
(let [props (nth argv 1 nil)
(let [props (nth argv first nil)
hasprops (or (nil? props) (map? props))
jsprops (convert-props (if hasprops props) parsed)
first-child (if hasprops 2 1)]
first-child (+ first (if hasprops 1 0))]
(if (input-component? comp)
(-> [(reagent-input) argv comp jsprops first-child]
(with-meta (meta argv))
@ -253,17 +253,20 @@
(str "Invalid Hiccup form: "
(pr-str v) (comp/comp-name)))
(cond
(keyword-identical? tag :>)
(native-element #js{:name (nth v 1)} v 2)
(hiccup-tag? tag)
(let [n (name tag)
pos (.indexOf n ">")]
(if (== pos -1)
(native-element (cached-parse n) v)
(native-element (cached-parse n) v 1)
;; Support extended hiccup syntax, i.e :div.bar>a.foo
(recur [(subs n 0 pos)
(assoc v 0 (subs n (inc pos)))])))
(instance? NativeWrapper tag)
(native-element (.-comp tag) v)
(native-element (.-comp tag) v 1)
:else (reag-element tag v))))

View File

@ -451,7 +451,8 @@
(def ndiv (.' js/React
createClass
#js{:render
#js{:displayName "ndiv"
:render
(fn []
(this-as
this
@ -484,6 +485,32 @@
(is (= (rstr [:div "a" "b" [:div "c"]])
(rstr [d2 "a" "b" [:div "c"]])))))
(deftest test-adapt-class-2
(let [d1 ndiv
d2 "div"]
(is (= (rstr [:div])
(rstr [:> d1])))
(is (= (rstr [:div "a"])
(rstr [:> d1 "a"])))
(is (= (rstr [:div "a" "b"])
(rstr [:> d1 "a" "b"])))
(is (= (rstr [:div.foo "a"])
(rstr [:> d1 {:class "foo"} "a"])))
(is (= (rstr [:div "a" "b" [:div "c"]])
(rstr [:> d1 "a" "b" [:div "c"]])))
(is (= (rstr [:div])
(rstr [:> d2])))
(is (= (rstr [:div "a"])
(rstr [:> d2 "a"])))
(is (= (rstr [:div "a" "b"])
(rstr [:> d2 "a" "b"])))
(is (= (rstr [:div.foo "a"])
(rstr [:> d2 {:class "foo"} "a"])))
(is (= (rstr [:div "a" "b" [:div "c"]])
(rstr [:> d2 "a" "b" [:div "c"]])))))
(deftest test-reactize-component
(let [ae r/as-element
ce r/create-element