第二句import SimpleStorageContract from '../build/contracts/SimpleStorage.json'导入的实际上是上步合约代码编译后产生的json文件,该文件中包含两个重要信息:一个是abi字段,通俗讲就是合约代码编译后产生的二进制接口,其中会声明合约代码暴露的可供调用的接口;另一个是bytecode字段,为合约代码的十六进制码。通过这两个重要信息就可以对一个合约进行相应操作。
instantiateContract() { /* * SMART CONTRACT EXAMPLE * * Normally these functions would be called in the context of a * state management library, but for convenience I've placed them here. */
// Stores a given value, 5 by default. // return simpleStorageInstance.set(5, {from: accounts[0]}) return; }).then((result) => { // Get the value from the contract to prove it worked. return simpleStorageInstance.get.call(accounts[0]) }).then((result) => { // Update state with the result. console.log(result); returnthis.setState({ storageValue: result.c[0] }) }) }) }
render() { return ( <divclassName="App"> <navclassName="navbar pure-menu pure-menu-horizontal"> <ahref="#"className="pure-menu-heading pure-menu-link">Truffle Box</a> </nav> <mainclassName="container"> <divclassName="pure-g"> <divclassName="pure-u-1-1"> <h1>Good to Go!</h1> <p>Your Truffle Box is installed and ready.</p> <h2>Smart Contract Example</h2> <p>If your contracts compiled and migrated successfully, below will show a stored value of 5 (by default).</p> <p>Try changing the value stored on <strong>line 59</strong> of App.js.</p> <p>The stored value is: {this.state.storageValue}</p> </div> </div> </main> <inputref="myvalue"className="myinput"/> <button className="mybutton" onClick={() => { var num = Number(this.refs.myvalue.value); console.log("点击了button"); console.log(num); simpleStorageInstance.set(num, {from: this.state.web3.eth.accounts[0]}).then(() => { console.log("数据修改成功"); simpleStorageInstance.get.call(this.state.web3.eth.accounts[0]).then((result) => { console.log("数据读取成功"); console.log(result); // 修改状态变量的值,在react中,一旦状态变量的值发生变化,就会调用render函数重新渲染UI this.setState({ storageValue: result.c[0] }) }); }) }} style={{height: 40,marginLeft: 50}}>修改合约数据</button> </div> ); } }