@blocklet/ui-react
Version:
Some useful front-end web components that can be used in Blocklets.
132 lines (102 loc) • 4.19 kB
Markdown
本指南将引导你逐步安装 @blocklet/ui-react 库并渲染你的第一个组件。目标是在最短的时间内在你的应用程序中拥有一个功能完备的 `Header` 和 `Footer`。
在继续之前,请确保你的开发环境中已安装以下内容:
* 一个可正常工作的 React 项目。
* Node.js 和一个包管理器(npm 或 yarn)。
首先,使用你偏好的包管理器将 `@blocklet/ui-react` 包添加到你的项目中。
使用 npm:
```bash npm
npm install @blocklet/ui-react
```
使用 yarn:
```bash yarn
yarn add @blocklet/ui-react
```
`Header` 和 `Footer` 组件的设计旨在简化使用,无需任何初始配置即可渲染。它们会自动从 blocklet 的元数据中获取数据。
1. 将 `Header` 和 `Footer` 组件导入到你的主应用程序文件(例如 `App.js`)中。
2. 将它们分别放置在应用程序布局的顶部和底部。
```jsx App.js icon=logos:react
import React from 'react';
import Header from '@blocklet/ui-react/lib/Header';
import Footer from '@blocklet/ui-react/lib/Footer';
function App() {
return (
<div>
<Header />
<main style={{ padding: '20px', minHeight: 'calc(100vh - 128px)' }}>
{/* 你的应用程序内容放在这里 */}
<h1>Welcome to My Blocklet</h1>
</main>
<Footer />
</div>
);
}
export default App;
```
这些组件会自动从 `window.blocklet` 元数据对象中检索配置详情(如应用名称、徽标和导航链接),该对象由 Blocklet Server 环境注入。
此外,`Header` 组件还会智能地渲染额外的控件:
* 如果 `SessionContext` 可用,则会显示**用户会话管理器**。
* 如果 `LocaleContext` 可用,则会显示**语言选择器**。
在开发、测试或需要覆盖默认元数据的情况下,你可以使用 `blockletMeta` 属性直接向组件传递一个配置对象。
```jsx App.js icon=logos:react
import React from 'react';
import Header from '@blocklet/ui-react/lib/Header';
const customBlockletMeta = {
appName: 'My Custom App',
appLogo: 'https://path.to/your/logo.png',
navigation: [
{
title: 'Home',
link: '/',
},
{
title: 'Documentation',
link: '/docs',
},
],
};
function App() {
return (
<div>
<Header blockletMeta={customBlockletMeta} />
{/* ... 你的应用程序的其余部分 */}
</div>
);
}
```
这种方法允许你覆盖全局 `window.blocklet` 对象提供的任何数据,从而精确控制组件的外观和行为。
`Header` 组件右侧包含一个 `addons` 区域,你可以对其进行自定义,以包含你自己的组件,例如操作按钮或自定义链接。
`addons` 属性接受一个函数作为参数,该函数接收默认的附加组件。这允许你在现有组件前后添加新组件或完全替换它们。
```jsx CustomHeader.js icon=logos:react
import React from 'react';
import Header from '@blocklet/ui-react/lib/Header';
import Button from '@mui/material/Button'; // 使用 Material-UI 的示例
function CustomHeader() {
return (
<Header
addons={existingAddons => {
return [
<Button
key="custom-action"
variant="contained"
color="primary"
size="small"
style={{ marginRight: 8 }}>
Custom Action
</Button>,
...existingAddons, // 重要:保留默认的 session/locale 附加组件
];
}}
/>
);
}
```
在此示例中,一个自定义按钮被添加到了现有附加组件的前面。通过包含 `...existingAddons`,你可以确保默认的会话和语言区域控件保持可见。
你已成功安装 `@blocklet/ui-react` 库,渲染了默认的 `Header` 和 `Footer` 组件,并学会了如何提供自定义配置和附加组件。
掌握了这些基础知识后,你现在可以开始探索该库中提供的全部组件了。有关布局、用户管理和实用工具组件的详细文档,请继续阅读 [组件](./components.md) 部分。