区块链

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

2018-04-05  本文已影响16人  金牛茶馆

基于智能合约+react 开发Dapp

引入初始化合约

src/app.js

import Employer from './components/Employer';

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

编辑合约

contracts/Payroll.sol
修改后记得重新部署

truffle migrate --reset 

添加前端组件

src/commponents/Employer.js

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

# 引入 antd 组件
import { Layout, Menu, Spin, Alert } from 'antd';
# 引入 antd.css 文件
import 'antd/disy/antd.css'
# 提取Layout中的组件
const { Header, Content, Footer } = Layout;
上一篇下一篇

猜你喜欢

热点阅读