我想通过Cloudflare以太坊网关访问以太坊区块链。我正在尝试使用web3 react库,但useWeb3React
不返回具有provider
属性的对象。
codesandbox.io
index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import Web3 from "web3";
import { Web3ReactProvider } from "@web3-react/core";
import App from "./App";
function getLibrary(provider) {
const web3Provider = new Web3.providers.HttpProvider(
"https://cloudflare-eth.com"
);
const web3 = new Web3(web3Provider);
return web3;
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<Web3ReactProvider getLibrary={getLibrary}>
<App />
</Web3ReactProvider>
</StrictMode>,
rootElement
);
App.js
import { useWeb3React } from "@web3-react/core";
import "./styles.css";
export default function App() {
const web3React = useWeb3React();
console.log({ web3React });
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
库中存在一个问题,该问题描述了此处的解决方案的确切问题:https://github.com/NoahZinsmeister/web3-react/issues/126#issuecomment-78305749
似乎你必须在你的App.js中使用任何你想使用的连接器来调用web3React.activate()
。例如,使用@web3 react/injected连接器:
import { useWeb3React } from "@web3-react/core";
import { InjectedConnector } from "@web3-react/injected-connector";
import "./styles.css";
export default function App() {
const web3React = useWeb3React();
web3React.activate(new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42]
}));
console.log({ web3React });
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}