表单
import axios from 'axios'
import React, { useState } from 'react'
import '../css/P8.css'
export default function P8() {
const [student, setStudent] = useState({name:'', sex:'男', age:18})
const [message, setMessage] = useState('')
const options = ['男', '女']
const jsx = options.map(e => <option key={e}>{e}</option>)
// e 事件对象, e.target 事件源
function onChange(e : React.ChangeEvent<HTMLInputElement|HTMLSelectElement>) {
setStudent((old)=>{
// 返回的新值,不能与旧值是同一个对象
return {...old, [e.target.name]:e.target.value}
})
}
async function onClick() {
const resp = await axios.post('http://localhost:8080/api/students', student)
setMessage(resp.data.data)
}
//className是jsx语法,相当于html标签里面的class,success代表是响应成功时的效果显示
const messageJsx = message && <div className='success'>{message}</div>
return (
<form>
<div>
<label>姓名</label>
<input type="text" value={student.name} onChange={onChange} name='name'/>
</div>
<div>
<label>性别</label>
<select value={student.sex} onChange={onChange} name='sex'>
{jsx}
</select>
</div>
<div>
<label>年龄</label>
<input type="text" value={student.age} onChange={onChange} name='age' />
</div>
<div>
<input type='button' value='新增' onClick={onClick}/>
</div>
{messageJsx}
</form>
)
}
2. React 进阶
1) Ant Design
react 组件库
-
官网地址:Ant Design - The world's second most popular React UI framework
-
镜像地址1:Ant Design - The world's second most popular React UI framework
-
镜像地址2:Ant Design - The world's second most popular React UI framework
入门
安装
npm install antd
目前版本是 "antd": "^5.10.2"
引入样式,在index.css 文件中加入
@import '~antd/dist/reset.css';
引入 antd 组件
import { Button } from "antd";
export default function A1() {
return <Button type='primary'>按钮</Button>
}
国际化
试试其它组件
import { Button, Modal } from "antd";
export default function A1() {
//Modal代表对话框组件标签
return <Modal open={true} title='对话框'>内容</Modal>
}
发现确定和取消按钮是英文的,这是因为 antd 支持多种语言,而默认语言是英文
要想改为中文,建议修改最外层的组件 index.tsx
// ...
import { ConfigProvider } from 'antd'
import zhCN from 'antd/es/locale/zh_CN'
root.render(
<ConfigProvider locale={zhCN}>
<A1></A1>
</ConfigProvider>
)
表格
import { Table } from 'antd'
import { ColumnsType, TablePaginationConfig } from "antd/es/table";
import axios from 'axios'
import { useEffect, useState } from 'react'
import { R, Student } from '../model/Student'
export default function A3() {
const [students, setStudents] = useState<Student[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
async function getStudents() {
const resp = await axios.get<R<Student[]>>(
'http://localhost:8080/api/students'
)
setStudents(resp.data.data)
setLoading(false)
}
getStudents()
}, [])
// title: 列标题 dataIndex: 要关联的属性名
const columns: ColumnsType<Student> = [
{
title: '编号',
dataIndex: 'id',
},
{
title: '姓名',
dataIndex: 'name',
},
{
title: '性别',
dataIndex: 'sex',
},
{
title: '年龄',
dataIndex: 'age',
},
]
// columns: 列定义
// dataSource: 数据源,一般是数组包对象
// rowKey: 作为唯一标识的属性名
// loading: 显示加载图片
return (
<Table
columns={columns}
dataSource={students}
rowKey='id'
loading={loading}></Table>
)
}