【问题标题】:React HOC wrapping with Clojurescript and Reagent使用 Clojurescript 和 Reagent 进行 React HOC 包装
【发布时间】:2017-08-27 22:02:27
【问题描述】:

我正在尝试重新使用 react-google-maps 中的组件并实现文档中的简单地图示例:https://tomchentw.github.io/react-google-maps/basics/simple-map

但是,我被 withGoogleMap 包装 GoogleMap 组件的高阶组件 (HOC) 阻止。我尝试使用 Reagent 调整类并按如下方式使用它们:

(def GoogleMap (adapt-react-class js/ReactGoogleMaps.GoogleMap))
(def withGoogleMap (adapt-react-class js/ReactGoogleMaps.withGoogleMap))

(defn Map [props]
  [withGoogleMap
   [GoogleMap props]])

代替以下Javascript:

const Map = withGoogleMap(props => (
  <GoogleMap
     {... props}
  >
  </GoogleMap>
));

没有成功。 (我收到以下错误withGoogleMap(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.)。

【问题讨论】:

    标签: clojurescript reagent


    【解决方案1】:

    应该使用包装组件调用的withGoogleMap HOC is a function。要实现simple map example,还需要为要包装的GoogleMap 组件提供props。这可以通过使用adapt-react-class 使组件适应试剂、实现CLJS 组件并在调用HOC 之前使用reactify-component“转换回来”来实现。

    (ns simple-map.views
      (:require [reagent.core :refer [adapt-react-class 
                                      create-element 
                                      reactify-component]]
                react-google-maps))
    
    (defn my-google-map []
      (let [google-map (adapt-react-class react-google-maps/GoogleMap)]
        [google-map {:defaultZoom   18
                     :defaultCenter {:lat 61.4481532
                                     :lng 23.8608644}}]))
    
    (defn MyMap [props]
      (let [m (-> my-google-map
                  reactify-component
                  react-google-maps/withGoogleMap
                  adapt-react-class)]
        [m props]))
    
    (defn main-panel []
      (let [container-element (create-element "div" #js{:style (clj->js {:height "768px" :width "1024px"})})
            map-element       (create-element "div" #js{:style (clj->js {:height "768px" :width "1024px"})})]
        (fn []
          [:div
           [MyMap {:containerElement container-element
                   :mapElement       map-element}]])))
    

    请注意,我使用 the experimental :npm-deps support 来要求 react-google-maps

    【讨论】:

    • 谢谢!这可能是我写的最长的 React 互操作了!我注意到您可以在 (create-element "div" (clj-&gt;js {:style {:height "768px" :width "1024px"}})) 中简化 create-element
    • @sebastie 没问题! (我注意到您已经回答了我对您的评论提出的问题)
    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    相关资源
    最近更新 更多