You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React项目中实现TronLink钱包连接?

在React项目中实现TronLink钱包连接(基于TronWeb)

核心原理

TronLink钱包会在浏览器的window对象中注入tronWeb实例和tronLink对象,无需手动创建全新的TronWeb实例,直接利用钱包注入的实例即可完成交互。

步骤1:安装TronWeb依赖

虽然TronLink会注入实例,但为了类型提示或离线开发时的类型检查,建议安装官方包:

npm install tronweb
# 或
yarn add tronweb

步骤2:实现钱包连接逻辑

在React组件中,你可以通过以下流程完成连接:

  • 检查TronLink是否已安装
  • 请求授权账户
  • 同步账户信息与TronWeb实例状态

以下是完整的函数组件示例:

import { useState, useEffect } from 'react';
import TronWeb from 'tronweb';

function TronLinkConnect() {
  const [account, setAccount] = useState('');
  const [isConnected, setIsConnected] = useState(false);
  const [tronWebInstance, setTronWebInstance] = useState(null);

  // 检查钱包是否安装
  const checkTronLinkInstalled = () => {
    return window.tronLink && window.tronWeb?.ready;
  };

  // 连接钱包
  const connectWallet = async () => {
    if (!checkTronLinkInstalled()) {
      alert('请先安装TronLink钱包');
      return;
    }

    try {
      // 请求账户授权
      const accounts = await window.tronLink.request({ method: 'tron_requestAccounts' });
      const selectedAccount = accounts[0];
      
      // 获取钱包注入的TronWeb实例
      const injectedTronWeb = window.tronWeb;
      // 验证实例有效性
      if (injectedTronWeb.defaultAddress.base58 === selectedAccount) {
        setAccount(selectedAccount);
        setIsConnected(true);
        setTronWebInstance(injectedTronWeb);
      }
    } catch (error) {
      console.error('连接失败:', error);
      alert('用户拒绝授权或连接出错');
    }
  };

  // 监听账户切换
  useEffect(() => {
    if (!window.tronWeb) return;

    const handleAccountChange = (newAccounts) => {
      if (newAccounts.length > 0) {
        setAccount(newAccounts[0]);
        setIsConnected(true);
        setTronWebInstance(window.tronWeb);
      } else {
        setAccount('');
        setIsConnected(false);
        setTronWebInstance(null);
      }
    };

    const handleNetworkChange = () => {
      console.log('网络已切换:', window.tronWeb.fullNode.host);
      // 可根据需要更新网络相关状态
    };

    // 绑定事件监听
    window.tronWeb.on('accountsChanged', handleAccountChange);
    window.tronWeb.on('networkChanged', handleNetworkChange);

    // 组件卸载时移除监听
    return () => {
      window.tronWeb.removeListener('accountsChanged', handleAccountChange);
      window.tronWeb.removeListener('networkChanged', handleNetworkChange);
    };
  }, []);

  // 页面加载时自动检测已连接状态
  useEffect(() => {
    if (checkTronLinkInstalled() && window.tronWeb.defaultAddress.base58) {
      setAccount(window.tronWeb.defaultAddress.base58);
      setIsConnected(true);
      setTronWebInstance(window.tronWeb);
    }
  }, []);

  return (
    <div>
      {isConnected ? (
        <div>
          <p>已连接账户:{account}</p>
          <p>当前网络:{tronWebInstance?.fullNode.host.includes('shasta') ? 'Shasta测试网' : '主网'}</p>
        </div>
      ) : (
        <button onClick={connectWallet}>连接TronLink钱包</button>
      )}
    </div>
  );
}

export default TronLinkConnect;

关键注意事项

  • 不要手动创建TronWeb实例:TronLink注入的实例已经和钱包绑定了签名、账户等逻辑,手动创建的实例无法完成钱包签名操作。
  • 事件监听:务必监听accountsChanged和networkChanged事件,确保页面状态与钱包状态同步。
  • 错误处理:要捕获用户拒绝授权、钱包未安装等异常场景,提升用户体验。

内容的提问来源于stack exchange,提问作者Akachi1325

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 00:02:51