尝试将应用程序洞察添加到您可以使用 React Hooks 的子组件中。
按照以下步骤实现:
在 React 中添加应用洞察参考 here
在您的 react 应用中添加应用洞察后尝试创建上下文文件,如 AppInsightsContext.js
import React, { createContext } from "react";
import { reactPlugin } from "./AppInsights";
const AppInsightsContext = createContext(reactPlugin);
const AppInsightsContextProvider = ({ children }) => {
return (
<AppInsightsContext.Provider value={reactPlugin}>
{children}
</AppInsightsContext.Provider>
);
};
export { AppInsightsContext, AppInsightsContextProvider };
现在,我们有一个设置 reactPlugin 的组件。我们需要将它添加到我们的 react 应用程序中。
在 Layout/index.js 文件中,我们需要将上下文设置为高。
const LayoutWithContext = ({ location, children }) => (
< AppInsightsContextProvider>
<>
<Headroom
upTolerance={10}
downTolerance={10}
style={{ zIndex: "20", height: "6.5em" }} >
< Header location={location} />
< /Headroom>
< Container text>{children}</Container>
< Footer />
</>
< /AppInsightsContextProvider>
);
上下文现在正在使用中,所有 children 组件都可以在我们的子组件中访问它。
如果您想使用 React 插件的标准页面交互跟踪,您可以将它与 HOC(高阶组件)结合使用
import React from "react";
import Headroom from "react-headroom";
import { Container } from "semantic-ui-react";
import Footer from "../Footer";
import Header from "../Header";
import "semantic-ui-css/semantic.min.css";
import { AppInsightsContextProvider } from "../../AppInsightsContext";
import withAppInsights from "../../AppInsights";
const Layout = withAppInsights(({ location, children }) => (
<>
<Headroom
upTolerance={10}
downTolerance={10}
style={{ zIndex: "20", height: "6.5em" }} >
<Header location={location} />
</Headroom>
<Container text>{children}</Container>
<Footer />
</>
));
const LayoutWithContext = ({ location, children }) => (
<AppInsightsContextProvider>
<Layout location={location} children={children} />
</AppInsightsContextProvider>
);
export default LayoutWithContext;
将上下文公开为 Hook
我们可以使用新的 Context-provided react 插件做的最后一件事是让它更容易访问,为此我们将使用 useContext Hook。为此,只需更新AppInsightsContext.js:
const useAppInsightsContext = () => useContext(AppInsightsContext);
创建用于跟踪事件的 Hook 参考 here
更多信息请参考this article