如何在ReactJS中使用全局javascript变量?

如何在ReactJS中使用全局javascript变量?,reactjs,Reactjs,我在顶层src目录中有一个文件variables.js,它声明了一个全局变量 declare var the_top; 在一个组件中,我想访问这个变量,但它声称它没有声明 import React, {useEffect, useState} from "react"; import {the_top} from "../variables"; const TopElement = (props) => { const [topElement, setTopElement] =

我在顶层src目录中有一个文件variables.js,它声明了一个全局变量

declare var the_top;
在一个组件中,我想访问这个变量,但它声称它没有声明

import React, {useEffect, useState} from "react";
import {the_top} from "../variables";

const TopElement = (props) => {
    const [topElement, setTopElement] = useState();

    the_top = "test";
给予


variables.js
中,使用
export var\u top
。 然后使用
import{the_top}从./variables'
请记住,导入变量会使其只读,因此,您将无法执行
the_top='blabla'

如果要使变量正确地全局化,请将其指定给window:
window.the\u top='test'
然后使用
console.log(window.the\u top)


还有,声明不是一件事,而是JS。只有在typescript中使用
export default\u top
声明类型,才不需要解构。
只需键入
从“../variables”导入_top
(只能导出一个默认变量)
如上所述,使用
窗口。全局变量的_top

无论如何,所有变量都需要导出,以便在另一个文件中使用。

默认导出可以使用,但我需要在该文件中导出更多变量。无法默认导出倍数我不明白这一点。当我写export var时,_top=“bla”;和useffect控制台中的.log(顶部);它将“bla”打印到控制台,但当我将_top=“blabla”I放在该console.log之前时,再次得到引用错误。当我写入window.the_top=“blabla”时,我没有得到引用错误,但console.log仍然只打印“bla”
ReferenceError: assignment to undeclared variable the_top