分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

React Native 调用 Web3(1.x) 的正确姿势

发布时间:2023-09-06 02:15责任编辑:董明明关键词:WebReact

1 创建项目

react-native init lm1cd lm1

2 安装依赖包

yarn add node-libs-browser

3 创建 rn-cli.config.js 脚本

const extraNodeModules = require(‘node-libs-browser‘);module.exports = { ?extraNodeModules,};

4 创建 global.js ,引入公用包

global.Buffer = require(‘buffer‘).Buffer;global.process = require(‘process‘);if (typeof btoa === ‘undefined‘) { ???global.btoa = function (str) { ?????return new Buffer(str, ‘binary‘).toString(‘base64‘); ???}; ?} ???if (typeof atob === ‘undefined‘) { ???global.atob = function (b64Encoded) { ?????return new Buffer(b64Encoded, ‘base64‘).toString(‘binary‘); ???}; ?}

5 在 app.js 中引入 global

import ‘./global‘;

6 安装 babel-preset-es2015

yarn add --dev babel-cli babel-preset-es2015

安装加密用包

yarn add react-native-crypto react-native-randombytes

安装兼容工具

yarn add --dev tradle/rn-nodeify

link

react-native link 

生成兼容js

./node_modules/.bin/rn-nodeify --hack --install

然后在 App.js 中引入

import ‘./shim.js‘import crypto from ‘crypto‘

7 安装 web3

yarn add web3

8  调用 web3

import Web3 from ‘web3‘;...componentWillMount() { ???const web3 = new Web3( ?????new Web3.providers.HttpProvider(‘https://mainnet.infura.io/‘) ???); ?????web3.eth.getBlock(‘latest‘).then(console.log) ?}

9 启动日志

react-native log-android

10 运行应用

react-native run-android

如果报错

contributors, removed 95 packages and updated 1064 packages in 156.737s/Users/Easy/Playground/lm1/node_modules/rn-nodeify/cmd.js:74 ?????if (err) throw err ??????????????^Error: ENOENT: no such file or directory, open ‘/Users/Easy/Playground/lm1/node_modules/rn-nodeify/shim.js‘
报错以后怎么办呢?
react-native link

然后 重新装 rn-nodefiy

yarn add --dev tradle/rn-nodeify

再运行

./node_modules/.bin/rn-nodeify --hack --install

这一次终于可以在根目录下成功生成 shim.js 了。

PS: windows下还要装 python 和 vcbuild.exe 一堆东西…… 我电脑装不下VS了……自行测试吧

React Native 调用 Web3(1.x) 的正确姿势

原文地址:https://www.cnblogs.com/qiyecao/p/9689223.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved