Sunflower 项目教程
1、项目介绍
Sunflower 是一个由 Alipay 行业技术团队开发的 React 组件库,专门用于简化 Ant Design (antd) 组件的使用。它通过提供一系列的“过程组件”(Process Components)来帮助开发者更高效地处理组件之间的关系,从而简化开发流程。Sunflower 支持 antd4 和 antd3,并且这些过程组件是从实际业务流程中提取出来的,可以直接使用。
2、项目快速启动
安装
首先,你需要在你的项目中安装 Sunflower:
npm install sunflower-antd --save
# 或者使用 yarn
yarn add sunflower-antd
基本使用
以下是一个简单的示例,展示了如何使用 Sunflower 中的 useFormTable
钩子来实现一个带有搜索功能的表格:
import React from 'react';
import { useFormTable } from 'sunflower-antd';
import { Input, Button, Table, Form } from 'antd';
export default (props) => {
const [formProps, tableProps] = useFormTable({
async search(values) {
const res = await request(values);
return res;
}
});
return (
<div>
<Form {...formProps}>
<Form.Item label="Username" name="username">
<Input placeholder="Username" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">Search</Button>
</Form.Item>
</Form>
<Table columns={[
{ title: 'Username', dataIndex: 'username', key: 'username' }
]} {...tableProps} />
</div>
);
};
开发环境启动
如果你想在本地开发环境中启动 Sunflower,可以按照以下步骤操作:
yarn install
yarn start
3、应用案例和最佳实践
案例一:表单与表格的联动
在许多业务场景中,表单和表格的联动是非常常见的。使用 Sunflower 的 useFormTable
钩子,你可以轻松实现这一功能。以下是一个完整的示例:
import React from 'react';
import { useFormTable } from 'sunflower-antd';
import { Input, Button, Table, Form } from 'antd';
export default (props) => {
const [formProps, tableProps] = useFormTable({
async search(values) {
const res = await request(values);
return res;
}
});
return (
<div>
<Form {...formProps}>
<Form.Item label="Username" name="username">
<Input placeholder="Username" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">Search</Button>
</Form.Item>
</Form>
<Table columns={[
{ title: 'Username', dataIndex: 'username', key: 'username' }
]} {...tableProps} />
</div>
);
};
案例二:分页与排序
Sunflower 还支持分页和排序功能。以下是一个示例,展示了如何使用 useFormTable
钩子来实现分页和排序:
import React from 'react';
import { useFormTable } from 'sunflower-antd';
import { Input, Button, Table, Form } from 'antd';
export default (props) => {
const [formProps, tableProps] = useFormTable({
async search(values, pagination, sorter) {
const res = await request(values, pagination, sorter);
return res;
}
});
return (
<div>
<Form {...formProps}>
<Form.Item label="Username" name="username">
<Input placeholder="Username" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">Search</Button>
</Form.Item>
</Form>
<Table columns={[
{ title: 'Username', dataIndex: 'username', key: 'username' }
]} {...tableProps} />
</div>
);
};
4、典型生态项目
Ant Design
Ant Design 是一个广泛使用的企业级 UI 设计语言和 React 组件库。Sunflower 是基于 Ant Design 开发的,因此与 Ant Design 的兼容性非常好。
React
React 是一个用于构建用户界面的 JavaScript 库。Sunflower 完全基于 React 开发,因此与 React 生态系统无缝集成。
React Hooks
Sunflower 大量使用了 React Hooks 来实现其功能。如果你对 React Hooks 有一定的了解,将更容易上手 Sunflower。
TypeScript
Sunflower 支持 TypeScript,并且提供了完整的类型定义文件。如果你使用 TypeScript 开发项目,Sunflower 将是一个非常好的选择。