我正在尝试使用React创建我的第一个dapp。我无法理解如何将Web3.js连接到React以及如何正确使用它。你能说明一下如何正确地做到这一点吗?也许我应该使用州。谢谢!
import React, { Component } from 'react';
import Web3 from 'web3';
import ABI from './web3/ABI'
class App extends Component {
web3Connection = () => {
let web3
if (window.ethereum) {
web3 = new Web3(window.ethereum);
try {
window.ethereum.enable().then(function() {});
} catch (e) {}
} else if (window.web3) {
web3 = new Web3(web3.currentProvider);
} else {
alert('You have to install MetaMask !');
}
web3.eth.defaultAccount = web3.eth.accounts[0];
const EthereumNoteContract = web3.eth.contract(ABI);
const EthereumNote = EthereumNoteContract.at('address');
}
addMyNote = (_text) => {
EthereumNote.addMyNote(_text, { value: 0 }, function(error, result) {
if (error) console.log(error);
else console.log(result)
});
}
render() {
return (
<div>
{this.web3Connection}
<button onClick={this.addMyNote}>Send</button>
</div>
)
}
}
假设您已安装metamask chrome扩展并已登录...还假设您已安装web3 lib ...
干得好:
import React from 'react';
import Web3 from 'web3'
export default class App extends React.Component {
state = {account: ''}
async loadBlockChain() {
const web3 = new Web3(Web3.givenProvider || 'http://localhost:8080')
const network = await web3.eth.net.getNetworkType();
console.log(network) // should give you main if you're connected to the main network via metamask...
const accounts = await web3.eth.getAccounts()
this.setState({account: accounts[0]})
}
componentDidMount() {
this.loadBlockChain()
}
render() {
return (
<div>
<p>Check out the the console....</p>
<p>Your account: {this.state.account}</p>
</div>
);
}
}