编辑
2025-04-20
编程语言-JavaScript
00
请注意,本文编写于 354 天前,最后修改于 0 天前,其中某些信息可能已经过时。

目录

文件后缀
Demo
父子传值

React 函数式组件配合 Hooks 已成为现代 React 开发的主流范式。本文通过一个完整的中心管理页面 Demo,系统展示函数式组件的核心 Hooks 用法。内容包括:useState 管理组件状态(分页参数、表格数据、弹窗显隐、表单值)、useMemo 缓存表单实例避免重复创建、useEffect 执行副作用操作(初始加载数据)。同时展示完整的 CRUD 交互流程:查询表单与表格联动、分页切换、新增/编辑弹窗表单提交、删除确认,以及父子组件传值(通过 props 解构 + useEffect 监听依赖变化)。文件后缀使用 .jsx

本文适用于使用 React 函数式组件进行业务开发的开发者。

文件后缀

shell
*.jsx

Demo

javascript
import React, {useEffect} from 'react'; import { Button, Page, Table, FilterPro, Message, Pagination, ConfirmButton, Dialog, Title, ProForm, Form, Placeholder, TitleCard } from '@sto/cn-ui'; import { addCenter, deleteCenterById, modifyCenter, queryCenterPage, queryRegionList } from "@/pages/ResourceAccess/CenterManage/service"; import DeptManage from "@/pages/ResourceAccess/CenterManage/DeptManage"; export default function CenterManage() { // React提供的一个性能优化Hook,主要用于在渲染过程中执行一些昂贵的计算,并且仅在依赖项发生变化时重新计算 // 参数1:函数 // 参数2:依赖项数组 // 效果:当依赖项数组内值发生变化,重新执行函数计算结果 // 查询表单 const form = React.useMemo(() => { // 执行耗时操作并返回 return FilterPro.createForm({ initialValues: { regionName: '', centerName: '', }, effects: () => { }, }); }, []); // State Hook让函数组件也可以有state状态, 并进行状态数据的读写操作 // 语法: const [xxx, setXxx] = React.useState(initValue) // 数组中第一个参数,是后面的值,第二个参数是改变值的方法 // 用法:setXxx((oldValue) => oldValue + 1) // 常量 const [params, setParams] = React.useState(form.values); const [regionMetas, setRegionMetas] = React.useState([]); // 表格 const [stateKey, setKeys] = React.useState({ keys: [], record: [], }); const [dataSource, setDataSource] = React.useState([]); const [currentPage, setCurrentPage] = React.useState(1); const [pageSize, setPageSize] = React.useState(5); const [pageTotal, setPageTotal] = React.useState(0); // 新增表单 const [addVisible, setAddVisible] = React.useState(false); const addForm = React.useMemo(() => { return FilterPro.createForm({ initialValues: { regionId: '', centerName: '', }, effects: () => { }, }); }, []); const [addFormParams, setAddFormParams] = React.useState(addForm.values); // 编辑表单 const [updVisible, setUpdVisible] = React.useState(false); const updForm = React.useMemo(() => { return FilterPro.createForm({ initialValues: { id: null, regionId: '', centerName: '', }, effects: () => { }, }); }, []); const [updFormParams, setUpdFormParams] = React.useState(updForm.values); // useEffect 允许你在组件渲染后执行副作用操作,像数据获取这种操作就属于副作用 // 参数1:函数 // 参数2:依赖项数组 // 效果:当依赖项数组内值发生变化,重新执行副作用操作 useEffect(() => { loadCenterPage(currentPage, pageSize, params).then(); }, []); // 远程调用 const loadCenterPage = async (currentPage, pageSize, queryParams) => { const args = { pageIndex: currentPage, pageSize: pageSize, requestModel: { regionName: queryParams?.regionName, centerName: queryParams?.centerName, } }; const data = await queryCenterPage(args); const total = data.total; const records = data.records; setCurrentPage(currentPage); setPageSize(pageSize); setPageTotal(total); setDataSource(records) } // 远程调用 const deleteCenter = async (id) => { await deleteCenterById({id: id}).then(data => { Message.success("操作成功"); loadCenterPage(1, pageSize, params).then(); }); } // 远程调用 const onAddCenterClick = async () => { const data = await queryRegionList(); const options = []; for (let dataKey in data) { options.push({label: data[dataKey]?.regionName, value: data[dataKey]?.regionId}); } setRegionMetas(options) addFormParams.regionId = ''; addFormParams.centerName = ''; setAddFormParams(addFormParams) setAddVisible(true); } // 远程调用 const onUpdCenterClick = async (record) => { const data = await queryRegionList(); const options = []; for (let dataKey in data) { options.push({label: data[dataKey]?.regionName, value: data[dataKey]?.regionId}); } setRegionMetas(options) updFormParams.id = record.id; updFormParams.regionId = record.regionId; updFormParams.centerName = record.centerName; setUpdFormParams(updFormParams => updFormParams) setUpdVisible(true); } // 渲染的内容 return ( <Page> <TitleCard title="中心管理" hasGutter> <FilterPro form={form} cacheSearch onSearch={setParams} extendButtons={<> <Button type={'primary'} onClick={onAddCenterClick}>新增</Button> </>} onChange={(values) => { // console.log('changed values:', values); }} onReset={() => { // Message.notice('onReset'); params.regionName = ''; params.centerName = ''; setParams(params); loadCenterPage(1, pageSize, params).then(); }} onSubmit={(values) => { // console.log('submit values:', values); // Message.notice('onSubmit'); loadCenterPage(1, pageSize, values).then(); }} /> <Table storageKey="centerManageId" primaryKey="id" columns={[ {title: '大区名称', dataIndex: 'regionName', width: 200}, {title: '大区编号', dataIndex: 'regionId', width: 200}, {title: '创建人', dataIndex: 'createUserName'}, ]} rowSelection={{ type: 'single', onChange(keys, record) { console.log('keys', keys, 'rowSelection.onChange', record); setKeys({keys, record}); }, selectedRowKeys: stateKey.keys, }} operateColumn={{ width: 200, buttons: [ (record, index) => { return ( <> <Button type={'primary'} onClick={() => onUpdCenterClick(record)} text>编辑 </Button> <ConfirmButton text type={'primary'} style={{marginLeft: 10}} btnContent="删除" dialogTitle="中心删除确认" dialogContent="确认删除当前中心?" successMsg={false} errorMsg={false} onConfirmSuccess={() => { deleteCenter(record.id).then(); }} /> </> ); }, ], }} dataSource={dataSource} /> <Pagination currentPage={currentPage} onChange={(value) => { setCurrentPage(value) loadCenterPage(value, pageSize, params).then(); }} pageSize={pageSize} onPageSizeChange={(value) => { setPageSize(value) loadCenterPage(1, value, params).then(); }} totalCount={pageTotal} pageSizeOptions={[5, 10, 15]} showJump={false} /> <Dialog hasGutter visible={addVisible} title={'新增中心'} closeMode={['close', 'mask', 'esc']} size={'small'} onClose={() => setAddVisible(false)} onCancel={() => setAddVisible(false)} footer={false} > <Form form={addForm} onSubmit={(values) => { // console.error('values', values); addCenter(values).then(data => { Message.success('操作成功'); setAddVisible(false); loadCenterPage(1, pageSize, params).then(); }); }} onReset={() => { addFormParams.regionId = ''; addFormParams.centerName = ''; setAddFormParams(addFormParams); }} hasFooterSubmit footerConfig={{mode: 'block'}} formLayoutProps={{labelCol: {fixedSpan: 5}}} > </Form> </Dialog> <Dialog hasGutter visible={updVisible} title={'编辑中心'} closeMode={['close', 'mask', 'esc']} size={'small'} onClose={() => setUpdVisible(false)} onCancel={() => setUpdVisible(false)} footer={false} > <Form form={updForm} onSubmit={(values) => { console.error('values', values); modifyCenter(values).then(data => { Message.success('操作成功'); setUpdVisible(false); loadCenterPage(1, pageSize, params).then(); }); }} onReset={() => { updFormParams.regionId = ''; updFormParams.centerName = ''; setUpdFormParams(updFormParams); }} hasFooterSubmit footerConfig={{mode: 'block'}} formLayoutProps={{labelCol: {fixedSpan: 5}}} > </Form> </Dialog> </TitleCard> <TitleCard title="部门管理" hasGutter> {/*'?.'表达式,判断stateKey内是否有属性record,没有属性,则整个调用链返回undefined*/}s <DeptManage {...stateKey?.record}/> </TitleCard> </Page> ); }

父子传值

javascript
import React from 'react'; export default function ParentDemo() { const [helloValue, setHelloValue] = React.useState('Hello World!'); return <ChildDemo {...{name1: helloValue, name2: helloValue + 'hei hei!'}}/>; }
javascript
import React, {useEffect} from 'react'; // 写法1 export default function ChildDemo(props) { useEffect(() => { // 当父组件传入的name1、name2值改变的时候,执行某些方法 doSomething(); }, [props.name1, props.name2]); return <h1>Hello, {props.name2}</h1>; } // 写法2:使用了解构函数 export default function ChildDemo({name1, name2}) { useEffect(() => { // 当父组件传入的name1、name2值改变的时候,执行某些方法 doSomething(); }, [name1, name2]); return <h1>Hello, {name2}</h1>; }
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:Odboy

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 CC 4.0 BY-SA 许可协议。转载请注明出处!