gpt4 book ai didi

javascript - 从 React 类导出变量

转载 作者:行者123 更新时间:2023-11-29 16:32:30 24 4
gpt4 key购买 nike

在我的应用程序类内的 app.js 中,有一个我想导出到另一个模块的变量。我尝试了很多选择,但不幸的是,我并没有理解如何正确地做到这一点。请告诉我,如何做对?导出默认值已在我的类(class)中使用

export class App extends Component {
static propTypes = {
//somecode
};

constructor(...args: any): void {
super(...args);
}

render() {
// console.log('app render start');
const test = true;
return (
//somecode
);
}

componentDidMount() {
//somecode
}


componentDidUpdate(prevProps): void {
//somecode
}
}

在上面的例子中,我需要导出变量'test'

如有任何帮助,我将不胜感激。

最佳答案

假设您对 test 的意图是定义类似“项目常量”的东西(这是我从您使用 const 关键字中收集到的),那么您可以简单地在 App 类之外声明 test,然后以与导出类相同的方式将其从模块中导出:

应用程序.js
/*
Export test variable
*/
export const test = true;

/*
Export your App class
*/
export class App extends Component {
static propTypes = {
//somecode
};

constructor(...args: any): void {
super(...args);
}

render() {
/*
Access test variable in "global scope" inside render method
*/
console.log(`test is: ${ test }`);

// console.log('app render start');
// const test = true;
return (
//somecode
);
}

componentDidMount() {
//somecode
}


componentDidUpdate(prevProps): void {
//somecode
}
}

然后,您可以从项目中的另一个模块访问 test,如下所示:

我的模块.js
import { App, test, } from 'path/to/App';

console.log(`test is: ${ test }`);

关于javascript - 从 React 类导出变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54527717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com