大家好,我是张大鹏,今天又来给大家分享技术文章了。
今天要分享的是如何在React18中渲染修改用户界面,效果图如下:
要实现这个功能,我们先创建一个UserUpdate.tsx页面,然后在路由中进行注册:
const router = createBrowserRouter([
? ?{
? ? ? ?path: "/",
? ? ? ?element: ,
? ? ? ?errorElement: ,
? ? ? ?// 子路由
? ? ? ?children: [
? ? ? ? ? ?{
? ? ? ? ? ? ? ?//path: "/index",
? ? ? ? ? ? ? ?index: true, // 设置为首页
? ? ? ? ? ? ? ?element:
? ? ? ? ? ?},
? ? ? ? ? ?{
? ? ? ? ? ? ? ?path: "/user-list",
? ? ? ? ? ? ? ?element:
? ? ? ? ? ?},
? ? ? ? ? ?{
? ? ? ? ? ? ? ?path: "/user-update",
? ? ? ? ? ? ? ?element:
? ? ? ? ? ?}
? ? ? ?]
? ?},
? ?// 登录界面
? ?{
? ? ? ?path: "/login",
? ? ? ?element: ,
? ?},
]);
然后我们在用户列表界面中,当渲染表格的时候,增加一个按钮,当点击按钮的时候,我们保存当前按钮对应行的数据,然后跳转到修改用户页面:
const columns: ColumnsType = [
? ?{
? ? ? ?title: '用户名',
? ? ? ?dataIndex: 'username',
? ? ? ?key: 'username',
? ?},
? ?{
? ? ? ?title: '是否激活',
? ? ? ?dataIndex: 'is_active',
? ? ? ?key: 'is_active',
? ? ? ?render: (active) => (
? ? ? ?),
? ?},
? ?{
? ? ? ?title: '姓名',
? ? ? ?dataIndex: 'fullname',
? ? ? ?key: 'fullname',
? ?},
? ?{
? ? ? ?title: '角色',
? ? ? ?dataIndex: 'role',
? ? ? ?key: 'role',
? ?},
? ?{
? ? ? ?title: '性别',
? ? ? ?dataIndex: 'gender',
? ? ? ?key: 'gender',
? ?},
? ?{
? ? ? ?title: '年龄',
? ? ? ?dataIndex: 'age',
? ? ? ?key: 'age',
? ?},
? ?{
? ? ? ?title: '操作',
? ? ? ?key: 'action',
? ? ? ?render: (value, record, index) => (
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ?console.log("修改。。。", value, record, index)
? ? ? ? ? ? ? ? ? ?setJSON("user-update", record)
? ? ? ? ? ? ? ? ? ?navigate("/user-update")
? ? ? ? ? ? ? ?}}>
? ? ? ? ? ? ? ? ? ?修改
? ? ? ? ? ? ? ?详情
? ? ? ? ? ? ? ?修改
? ? ? ? ? ? ? ?删除
? ? ? ?),
? ?},
];
接着来到修改用户界面,读取要修改的用户信息,然后渲染在表单中:
// 重置表单
const onReset = () => {
? ?const user = getJSON("user-update")
? ?// 修改表单默认信息
? ?form.setFieldsValue({
? ? ? ?username: user.username,
? ? ? ?gender: user.gender,
? ? ? ?is_active: user.is_active,
? ? ? ?role: user.role,
? ? ? ?age: user.age,
? ? ? ?fullname: user.fullname,
? ?});
? ?// 设置激活状态
? ?setIsActive(user.is_active)
};
// 加载要修改的用户信息
useEffect(() => {
? ?// 设置标题
? ?document.title = "修改用户信息"
? ?onReset() // 重置表单
}, [])
表单的完整代码如下:
? ?{...layout}
? ?form={form}
? ?name="control-hooks"
? ?onFinish={onFinish}
? ?style={{maxWidth: 600}}
>
? ? ? ? ? ?placeholder="请选择性别"
? ? ? ?>
? ? ? ? ? ?男
? ? ? ? ? ?女
? ? ? ? ? ?保密
? ? ? ? setIsActive(checked)}/>
? ? ? ? ? ?placeholder="请选择角色"
? ? ? ?>
? ? ? ? ? ?管理员
? ? ? ? ? ?用户
? ? ? ? ? ?提交
? ? ? ? ? ?重置
表单需要的依赖变量如下:
// 表单信息
const [form] = Form.useForm();
// 是否激活
const [isActive, setIsActive] = useState(false)
const {Option} = Select;
// 表单布局
const layout = {
? ?labelCol: {span: 8},
? ?wrapperCol: {span: 16},
};
// 按钮布局
const tailLayout = {
? ?wrapperCol: {offset: 8, span: 16},
};
// 提交表单
const onFinish = (values: any) => {
? ?console.log(values);
};
最终,用户列表界面如下:
以上就是今天要分享的全部内容了,谢谢大家~
领取专属 10元无门槛券
私享最新 技术干货