美文网首页
使用React+AntD构建CRUD(增删改查)应用

使用React+AntD构建CRUD(增删改查)应用

作者: 南荣相如谈编程 | 来源:发表于2020-04-13 21:23 被阅读0次

概览

React 是什么?

React 是一个声明式,高效且灵活的用于构建用户界面的 JavaScript 库。使用 React 可以将一些简短、独立的代码片段组合成复杂的 UI 界面,这些代码片段被称作“组件”。

antd 是什么?

antd 是基于 Ant Design 设计体系的 React UI 组件库,主要用于研发企业级中后台产品。

目标

使用React+AntD构建一个非常简单CRUD应用程序,以便您更好地了解它的工作方式。

完整的 demo 代码请访问 https://github.com/zcqiand/crud

演示

列表页面

QQ20200402145823.png

添加页面

QQ20200402150132.png

编辑页面

QQ20200402150153.png

构建

创建React应用

Facebook创建了Create React App,该环境预先配置了构建React应用所需的一切。它将创建一个实时开发服务器,使用Webpack自动编译React,JSX和ES6,自动前缀CSS文件,并使用ESLint测试和警告代码中的错误。

create-react-app react-antd

安装完成后,移至新创建的目录并启动项目。

cd react-antd
npm start

一旦运行此命令,localhost:3000新的React应用程序将弹出一个新窗口。

QQ20200402151735.png

构建路由

安装

npm install react-router-dom

修改App.js代码,放入路由的代码

import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";

import GoodsIndex from "./goods/index";
import GoodsAdd from "./goods/add";
import GoodsEdit from "./goods/edit";


export default function App() {
return (
    <Router>
    <div>
        <ul>
        <li>
            <Link to="/">商品</Link>
        </li>
        </ul>
        <hr />
        <Switch>
        <Route exact path="/">
            <GoodsIndex />
        </Route>
        <Route path="/goods/add">
            <GoodsAdd />
        </Route>
        <Route path="/goods/:id/edit" render={(props) => <GoodsEdit {...props} />} />
        </Switch>
    </div>
    </Router>
)
}

安装AntD

npm install antd --save

构建列表页面

import React, { Component } from "react";
import { Table, Button } from 'antd';

export default class GoodsIndex extends Component {
constructor(props) {
    super(props)
    this.state = {
    items: []
    }
}

componentDidMount() {
    this.queryGoods()
}

queryGoods() {
    console.log('queryGoods');
    const url = "http://localhost:59367/examplemodule/goods"
    fetch(url, { method: "get" })
    .then(response => response.json())
    .then(result => {
        console.log(result)
        if (result.Code === 0) {
        this.setState({
            items: result.Result
        })
        }
    })
}

addGoods = () => {
    console.log('addGoods');
    window.location.pathname = "/goods/add";
}

editGoods = (id) => {
    console.log('editGoods');
    window.location.pathname = `/goods/${id}/edit`;
}

deleteGoods = (id) => {
    console.log('deleteGoods:' + id);
    const url = `http://localhost:59367/examplemodule/goods/${id}/delete`
    fetch(url, {
    method: "post",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    })
    .then(response => response.json())
    .then(result => {
        console.log(result)
        alert("删除成功")
        window.location.pathname = "/";
    })
}

render() {
    const items = this.state.items || []

    const columns = [
    {
        title: '名称',
        dataIndex: 'Name',
        key: 'Name',
    },
    {
        title: '描述',
        dataIndex: 'Describe',
        key: 'Describe',
    },
    {
        title: '操作',
        key: 'action',
        render: (record) => (
        <div>
            <Button type="link" onClick={() => this.editGoods(record.Id)}>编辑</Button>
            <Button type="link" onClick={() => this.deleteGoods(record.Id)}>删除</Button>
        </div>
        ),
    },
    ];

    return (
    <div>
        <Button type="primary" onClick={this.addGoods}>添加</Button>
        <Table columns={columns} dataSource={items} />
    </div>
    )
}
}

构建添加页面

import React, { Component } from "react";
import { Form, Input, Button } from 'antd';
import qs from 'qs';

const { TextArea } = Input;

export default class GoodsAdd extends Component {
render() {
    const onFinish = values => {
    console.log('onFinish:', values);
    const param = values
    console.log('param:' + qs.stringify(param));
    const url = "http://localhost:59367/examplemodule/goods/create"
    fetch(url, {
        method: "post",
        body: qs.stringify(param), // data can be `string` or {object}!
        headers: {
        "Content-Type": "application/x-www-form-urlencoded"
        }
    })
        .then(response => response.json())
        .then(result => {
        console.log(result)
        alert("添加成功")
        window.location.pathname = "/";
        })
    };

    const onFinishFailed = errorInfo => {
    console.log('onFinishFailed:', errorInfo);
    };

    return (
    <Form
        name="basic"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
    >
        <Form.Item
        label="名称"
        name="Name"
        rules={[{ required: true, message: '请填写名称!' }]}
        >
        <Input />
        </Form.Item>

        <Form.Item
        label="描述"
        name="Describe"
        rules={[{ required: true, message: '请填写你描述!' }]}
        >
        <TextArea rows={4} />
        </Form.Item>

        <Form.Item>
        <Button type="primary" htmlType="submit" onClick={this.createGoods}>
            新增
        </Button>
        </Form.Item>
    </Form>
    )
}
}

构建编辑页面

import React, { Component } from "react";
import { Form, Input, Button } from 'antd';
import qs from 'qs';

const { TextArea } = Input;

export default class GoodsEdit extends Component {
formRef = React.createRef();
constructor(props) {
    super(props)
    this.state = {
    item: {}
    }
}

componentDidMount() {
    this.getGoods(this.props.match.params.id)
}

getGoods(id) {
    console.log('getGoods');
    const url = `http://localhost:59367/examplemodule/goods/${id}`
    fetch(url, { method: "get" })
    .then(response => response.json())
    .then(result => {
        console.log(result)
        if (result.Code === 0) {
        this.setState({
            item: result.Result
        })
        this.formRef.current.setFieldsValue({
            Name: result.Result.Name,
            Describe: result.Result.Describe,
        });
        }
    })
}

render() {    
    const onFinish = values => {
    console.log('onFinish:', values);
    const param = values
    const id = this.props.match.params.id
    console.log('param:' + qs.stringify(param));
    const url = `http://localhost:59367/examplemodule/goods/${id}/update`
    fetch(url, {
        method: "post",
        body: qs.stringify(param), // data can be `string` or {object}!
        headers: {
        "Content-Type": "application/x-www-form-urlencoded"
        }
    })
        .then(response => response.json())
        .then(result => {
        console.log(result)
        alert("更新成功")
        window.location.pathname = "/";
        })
    };

    const onFinishFailed = errorInfo => {
    console.log('onFinishFailed:', errorInfo);
    };

    return (      
    <Form
        name="basic"
        ref={this.formRef}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
    >
        <Form.Item
        label="名称"
        name="Name"
        rules={[{ required: true, message: '请填写名称!' }]}
        >
        <Input ref={Name => this.Name = Name}/>
        </Form.Item>

        <Form.Item
        label="描述"
        name="Describe"
        rules={[{ required: true, message: '请填写你描述!' }]}
        >
        <TextArea rows={4} ref={Describe => this.Describe = Describe}/>
        </Form.Item>

        <Form.Item>
        <Button type="primary" htmlType="submit" onClick={this.createGoods}>
        更新
        </Button>
        </Form.Item>
    </Form>
    )
}
}

参考

相关文章

网友评论

      本文标题:使用React+AntD构建CRUD(增删改查)应用

      本文链接:https://www.haomeiwen.com/subject/tbohmhtx.html