简体   繁体   English

在整个 React 应用程序中全局共享辅助函数

[英]Sharing helper functions globally across the whole React app

How would one go about making global functions in React that you only have to import into one file that shares it across every page?一个 go 如何在 React 中制作全局函数,您只需将其导入到一个文件中,该文件在每个页面上共享它?

Right now I can have to import helper.tsx into each file where I want to use them in.现在我必须将helper.tsx导入到我想使用它们的每个文件中。

For example I have a helper.tsx file that exports functions as such:例如,我有一个导出函数的helper.tsx文件:

interface cookieProps {
  name: string;
  value: string;
  exdays: number;
}
export const getCookie = ({ name }: cookieProps) => {
  var i,
    x,
    y,
    ARRcookies = document.cookie.split(";");
  for (i = 0; i < ARRcookies.length; i++) {
    x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
    y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
    x = x.replace(/^\s+|\s+$/g, "");
    if (x == name) {
      return unescape(y);
    }
  }
  return "";
};

Now were I do import it into my App.tsx file like this:现在我将它导入到我的App.tsx文件中,如下所示:

import React, { useEffect } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";
import Cards from "./pages/Cards";
import { getCookie } from "./controllers/helpers";

const theme = createTheme({
  palette: {
    primary: {
      main: "#fff",
    },
    secondary: {
      main: "#f8f8f8",
    },
  })
export default function App() {
  return (
    <ThemeProvider theme={theme}>
        <BrowserRouter>
          <Navbar />
          <Routes>
            <Route path="/home" element={<Home />} />
            <Route path="/cards" element={<Cards />} />
            <Route path="*" element={<Home />} />
          </Routes>
          <Footer />
        </BrowserRouter>
    </ThemeProvider>
  );
}

I cannot call it from Home or Cards etc. When declared cookie imports are not initialised or used inside App.tsx I cannot access them.我无法从 Home 或 Cards 等调用它。当声明的 cookie 导入未初始化或在App.tsx中使用时,我无法访问它们。 I want to be able to call all of those helper functions from every page possible and not have to import them again.我希望能够从每个可能的页面调用所有这些辅助函数,而不必再次导入它们。

Should I make the imports into vars and call them as helper.getCookie ?我应该将导入导入vars并将它们称为helper.getCookie吗?

Bind that function into window , like window.getCookie = getCookie , or add to a helper object like window.helper = {getCookie() {...}}将 function 绑定到window中,例如window.getCookie = getCookie ,或添加到助手 object 中,例如window.helper = {getCookie() {...}}

p/s: I am using this method, not sure if that is a right way to do or if it affects whole website performance, but no problems so far p/s: 我正在使用这种方法,不确定这是否是正确的方法,或者它是否会影响整个网站的性能,但目前没有问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM