步骤
链接Metamask
定义Provider
实例化Web3
读取Metamask的当前账号和网络ID
切换网络

节点与与Metamask Infura.io Provider web3之间的关系图

web3文档参考
https://learnblockchain.cn/manuals

初始化项目,如果没有create-react-app请先安装
npx create-react-app my-web3
cd my-web3
npm start

安装web3
yarn add web3

当然在web3和react webpack-5 兼容这里有非常大的坑 修改import调取文件就可以解决
整理文章 /3715.html

修改App.js

import React, { Component } from 'react';
import Web3 from "web3/dist/web3.min"; //使用兼容版本的web3库文件
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  async componentDidMount() {
    //判断页面是否安装metamask
    if (typeof window.ethereum !== 'undefined') {
      const ethereum = window.ethereum
      //禁止自动刷新,metamask要求写的
      ethereum.autoRefreshOnNetworkChange = false

      try {
        //第一次链接Metamask
        //await 配合函数前加async
        const accounts = await ethereum.enable()
        console.log(accounts)

        //初始化Provider
        const provider = window['ethereum']
        //输出Provider全部类方法可以在浏览器查看
        console.log(provider)

        //获取网络ID
        console.log(provider.chainId)

        //实例化web3
        const web3 = new Web3(provider)
        console.log(web3)

        //账户切换监听
        ethereum.on('accountsChanged', function (accounts) {
          console.log("accountsChanged:" + accounts)
        })

        //网络切换监听
        ethereum.on('networkChanged', function (networkVersion) {
          console.log("networkChanged:" + networkVersion)
        })

      } catch (e) {

      }
    } else {
      console.log("没用安装mstamask")
    }
  }
  render() {
    return (
); } } export default App;