Zihao

Make small but daily progress

0%

0x06--智能合约开发之前端开发

基于智能合约+react 开发Dapp

引入初始化合约

src/app.js

1
import Employer from './components/Employer';

componentWillMount
instantiateContract 中初始化
render(){} 渲染页面

编辑合约

contracts/Payroll.sol

修改后记得重新部署

1
truffle migrate --reset 

添加前端组件

src/commponents/Employer.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import React, { Component } from 'react'
import { Card, Col, Row, Layout, Alert, message, Button } from 'antd';

import Common from './Common';

class Employer extends Component {
constructor( props ) {
super( props );
this.state = {};
}

componentDidMount() {
this.checkEmployee();
}

checkEmployee = async () => {
const { payroll, account, web3 } = this.props;

const balanceWei = await web3.eth.getBalance(account)
const employee = await payroll.employees.call( account,{
from: account
})


this.setState({
address: employee[ 0 ],
salary: web3.fromWei( employee[ 1 ].toNumber() ),
lastPaidDate: new Date( employee[ 2 ].toNumber() * 1000 ).toLocaleString(),
balance: web3.fromWei( balanceWei.toNumber() ),
})
}

getPaid = async () => {
const { payroll, account, web3 } = this.props;

await payroll.getPaid({from: account})

this.checkEmployee()
}

renderContent() {
const { salary, lastPaidDate, balance } = this.state;

if ( !salary || salary === '0' ) {
return <Alert message="你不是员工" type="error" showIcon/>;
}

return (
<div>
<Row gutter={16}>
<Col span={8}>
<Card title="薪水">{salary} Ether</Card>
</Col>
<Col span={8}>
<Card title="上次支付">{lastPaidDate}</Card>
</Col>
<Col span={8}>
<Card title="帐号金额">{balance} Ether</Card>
</Col>
</Row>

<Button
type="primary"
icon="bank"
onClick={this.getPaid}
>
获得酬劳
</Button>
</div>
);
}

render() {
const { account, payroll, web3 } = this.props;

return (
<Layout style={{ padding: '0 24px', background: '#fff' }}>
<Common account={account} payroll={payroll} web3={web3}/>
<h2>个人信息</h2>
{this.renderContent()}
</Layout>
);
}
}

export default Employer

组件选择

推荐使用[ant] ant.design

1
2
3
4
5
6
# 引入 antd 组件
import { Layout, Menu, Spin, Alert } from 'antd';
# 引入 antd.css 文件
import 'antd/disy/antd.css'
# 提取Layout中的组件
const { Header, Content, Footer } = Layout;

欢迎关注我的其它发布渠道