2015-01-31 4 views
3

Я пытаюсь проанализировать HTML с помощью CSS в Hiccup в проекте Reagent. Я использую Хикори. Когда я анализирую HTML с встроенным CSS, React выдает исключение.Как преобразовать HTML-тег со стилем в Hiccup? Проблемы с реакцией

 (map 
     as-hiccup (parse-fragment "<div style='color:red'>test</div>") 
    ) 

выше генерирует [:div {:style color:red} "test"] & Reactjs возвращает исключение из Reactjs:

Violation: The style prop expects a mapping from style properties to values, not a string.

[:div {:style {"color" "red"}} "test"] Я считаю, что должен быть возвращен вместо этого.

Вот вид код:

(ns main.views.job 
    (:require [reagent.core :as reagent :refer [atom]] 
        [hickory.core :refer [as-hiccup parse parse-fragment]])) 

(enable-console-print!) 

(defn some-view [uid] 
    [:div 
    (map as-hiccup (parse-fragment "<div style='color:red'>test</div>")) 
    ]) 
+0

Какая версия Hickory вы используете? – sbensu

+0

hickory "0.5.4" –

+0

Я пробовал минимальную версию, используя [mies] (https://github.com/swannodette/mies) и Hickory 0.5.4, и он [работал] (https://github.com/bensu/гикори-стека). Можете ли вы опубликовать исключение браузера, ваше 'project.clj' и объявление ns? – sbensu

ответ

2

Все репо here и она работает. Я добавил парсинг из тега стиля к карте для React в файле core.cljs:

(ns hickory-stack.core 
    (:require [clojure.string :as s] 
      [clojure.walk :as w] 
      [reagent.core :as reagent :refer [atom]] 
      [hickory.core :as h])) 

(enable-console-print!) 

(defn string->tokens 
    "Takes a string with syles and parses it into properties and value tokens" 
    [style] 
    {:pre [(string? style)] 
    :post [(even? (count %))]} 
    (->> (s/split style #";") 
     (mapcat #(s/split % #":")) 
     (map s/trim))) 

(defn tokens->map 
    "Takes a seq of tokens with the properties (even) and their values (odd) 
    and returns a map of {properties values}" 
    [tokens] 
    {:pre [(even? (count tokens))] 
    :post [(map? %)]} 
    (zipmap (keep-indexed #(if (even? %1) %2) tokens) 
      (keep-indexed #(if (odd? %1) %2) tokens))) 

(defn style->map 
    "Takes an inline style attribute stirng and converts it to a React Style map" 
    [style] 
    (tokens->map (string->tokens style))) 

(defn hiccup->sablono 
    "Transforms a style inline attribute into a style map for React" 
    [coll] 
    (w/postwalk 
    (fn [x] 
    (if (map? x) 
     (update-in x [:style] style->map) 
     x)) 
    coll)) 

;; Test Data 

(def good-style "color:red;background:black; font-style: normal ;font-size : 20px") 

(def html-fragment 
    (str "<div style='" good-style "'><div id='a' class='btn' style='font-size:30px;color:white'>test1</div>test2</div>")) 

;; Rendering 

(defn some-view [] 
    [:div (hiccup->sablono 
     (first (map h/as-hiccup (h/parse-fragment html-fragment))))]) 

(reagent/render-component [some-view] 
          (. js/document (getElementById "app")))