为ReactJs创建高阶组件

时间:2018-10-19 01:49:39

标签: reactjs

我正在尝试为我的React App创建一个HOC。但是,当我尝试包装原始组件时,typescript引发错误,抱怨找不到由高阶组件注入的属性。从逻辑上讲,我了解到我们需要告知打字稿将插入道具,但我无法确定语法。以下是我正在使用的代码。

    //Wrapper
    import * as React from 'react';
    let config = require('../appsettings.json')

    const withTelemetry = (WrappedComponent: any)  => {
        class CustomInsight extends React.Component{

            appInsight: Microsoft.ApplicationInsights.IAppInsights;


            componentDidMount(){
                if (appInsights.downloadAndSetup !== undefined) {
                    appInsights.downloadAndSetup({ instrumentationKey: config.instrumentationKey });

                }

                this.appInsight.trackEvent('Telemetry loaded. Using Azure Insights: ' + config.instrumentationKey);
            }

            trackPage = (name: string) => {

                this.appInsight.trackPageView(name);
            }

            render(){

                return (<WrappedComponent
                        {...this.props}
                        trackPage = {this.trackPage}                    
                        />)
            };

        }

        return CustomInsight;
    }

    export default withTelemetry;

以下是利用HOC的主要组件

// Dashboard page.
import * as React from 'react';
import { observable } from 'mobx';
import { observer, inject } from 'mobx-react';

import withTelemetry from '../../components/insight';


@observer class Dashboard extends React.Component {

  constructor(props: any) {
    super(props);
  }

  componentDidMount() {  
    this.props.trackPage('test');
  } 

  render() {
        //.. code commented for brevity
    );
  }
}


const WrappedDashboard = withTelemetry(Dashboard);

export default WrappedDashboard;

0 个答案:

没有答案