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

如何在React Native项目中实现Web3集成?

在React Native中集成Web3的实用方案

1. 安装必要依赖

React Native环境下直接用官方web3包可能存在兼容性问题,先安装核心包和适配工具:

# 安装web3核心包
npm install web3
# 处理网络状态检测(可选但推荐)
npm install @react-native-community/netinfo
# 解决Web3必需的随机数生成依赖
npm install react-native-randombytes
# 安装polyfill补全Node.js模块(如crypto)
npm install react-native-crypto node-libs-react-native

iOS端安装完成后,记得执行cd ios && pod install && cd ..。

2. 初始化Web3实例

在项目中创建一个Web3工具类(比如web3Service.js),统一管理节点连接:

import Web3 from 'web3';
import NetInfo from '@react-native-community/netinfo';

let web3Instance = null;

export const initWeb3 = async () => {
  // 先检测网络状态
  const networkState = await NetInfo.fetch();
  if (!networkState.isConnected) {
    throw new Error('请检查网络连接');
  }

  // 替换为你的Infura节点或自定义节点地址
  const provider = new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/你的项目ID');
  web3Instance = new Web3(provider);
  return web3Instance;
};

export const getWeb3 = () => {
  if (!web3Instance) {
    throw new Error('Web3未初始化,请先调用initWeb3');
  }
  return web3Instance;
};

3. 核心功能示例

获取账户ETH余额

import { getWeb3 } from './web3Service';

export const getAccountBalance = async (address) => {
  const web3 = getWeb3();
  const balance = await web3.eth.getBalance(address);
  // 转换为易读的ETH格式
  return web3.utils.fromWei(balance, 'ether');
};

调用ERC20合约余额查询

import { getWeb3 } from './web3Service';

// ERC20合约基础ABI片段
const ERC20_ABI = [
  {
    "constant": true,
    "inputs": [{ "name": "_owner", "type": "address" }],
    "name": "balanceOf",
    "outputs": [{ "name": "", "type": "uint256" }],
    "type": "function"
  }
];

export const getTokenBalance = async (tokenAddress, userAddress) => {
  const web3 = getWeb3();
  const contract = new web3.eth.Contract(ERC20_ABI, tokenAddress);
  const balance = await contract.methods.balanceOf(userAddress).call();
  return web3.utils.fromWei(balance, 'ether');
};

4. 常见坑点处理

  • Node.js模块缺失报错:如果遇到crypto、buffer等模块找不到的问题,在项目根目录创建metro.config.js添加配置:
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');

module.exports = mergeConfig(getDefaultConfig(__dirname), {
  resolver: {
    extraNodeModules: require('node-libs-react-native'),
  },
});
  • iOS构建失败:若react-native-randombytes导致编译错误,在iOS项目的Podfile中添加:
pod 'RNRandomBytes', :path => '../node_modules/react-native-randombytes'

之后重新执行pod install即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:55:18