【问题标题】:How to get variable (const?) value in other component in ReactJS?如何在 ReactJS 的其他组件中获取变量(const?)值?
【发布时间】:2019-05-27 09:57:41
【问题描述】:

我开始使用 React。我有一个主文件(App.js),所有逻辑都在其中,在该文件中,我添加了路由(,,,),这些路由通过 URL 从其他文件(仅内容)加载不同的页面。

在 App.js 构造函数中,我添加了 web3 包并将其写入变量(窗口、全局变量)中,因为这只是在其他组件文件中获取该变量的一种方法。我不想使用窗口变量,因为每个用户都可以看到。我想使用 const/var 变量,但在每个组件文件中获取该值,但我不想加载相同的 web3 库(或在每个组件文件中连接智能合约)。该怎么做?

【问题讨论】:

  • 你可以使用Redux
  • 可以使用上下文api

标签: javascript reactjs typescript web3


【解决方案1】:

假设您的意思是 web3 拥有的一切。在你的组件文件上

import React from 'react';
import Web3 from 'web3';

const ComponentA () => {
    // Do what ever you want with Web3 and react code here
};

export default ComponentA;

如果你想要你创建的 web3 的实例,也许你可以在它自己的文件中初始化 web3。

你自己的web3_instance.js

import Web3 from 'web3';

const web3Instance = new Web3();

export default web3Instance;

然后将其导入任何组件。

import React from 'react';
import web3Instance from '../path/to/web3instance.js';

const ComponentA () => {
    // Do what ever you want with web3Instance and react code here
};

export default ComponentA;

【讨论】:

    猜你喜欢
    • 2020-02-29
    • 2016-04-09
    • 2012-07-01
    • 2016-12-05
    • 1970-01-01
    • 2018-09-21
    • 2021-03-18
    • 1970-01-01
    • 2019-12-23
    相关资源
    最近更新 更多