将道具传递到高阶组件内的组件

时间:2020-04-07 22:22:14

标签: reactjs authentication react-leaflet higher-order-components

我试图了解如何将道具传递给由高阶组件包裹的组件。我有一个这样写的高阶组件:

import React from 'react'

function withAuth(Layer){

   return class AuthenticatedHOC extends React.Component{

      componentDidMount(){
         if (!this.props.token){
            authenticateEsri()
         } 
      }

      render(){
         return (
            <>
               {this.props.token && <Layer {...this.props} />}
            </>
         )
      }

   }

}

const mapStateToProps = state => ({
   token: state.data.layers.esri.access_token
})

export default compose(
   connect(mapStateToProps),
   withAuth
)

非常简单。 HOC检查redux存储区中是否存在身份验证令牌。如果不是,它将进行API调用以获取令牌。一旦进入,它将使用auth令牌作为道具渲染包装的组件。在此HOC中用作参数的平均分量如下所示:

import { withLeaflet, MapControl } from "react-leaflet";
import * as EsriLeaflet from "esri-leaflet";
import withEsriAuth from './withAuth'

class Layer extends MapControl {
   createLeafletElement(props) {
      const layer = EsriLeaflet[props.layerType]({
         ...props
      })
      return layer;
   }

   componentDidMount() {
      const { map } = this.props.leaflet;
      this.leafletElement.addTo(map);
   }
}

export default withEsriAuth(withLeaflet(Layer))

有些层需要一个auth令牌,有些则不需要。将令牌传递到不需要令牌的层会导致错误,不会将令牌传递到不需要令牌的层。我想要做的是将withEsriAuthEsriLeafletLayer组件分开。我希望每次我声明一个EsriLeafletLayer时,都能够决定是否使用auth HOC,而不是每次都将withEsriAuth包裹在Layer中。就目前而言,我可以这样声明一个组件:

<Layer url="somelayerurl.com" opacity={0.5} />

它将每次都运行身份验证。我宁愿export default withLeaflet(Layer),然后声明如下内容:

withAuth( <Layer url="somelayerurl.com" opacity={0.5} /> )

但是,这不起作用-告诉我函数不是有效的react子代。我知道该语法看起来有些古怪,而且必须有一种更适当的方式来编写此语法。

感谢阅读。

0 个答案:

没有答案