快速上手#
通过 npm 安装#
npm i @chatui/core -S
引入组件#
import React from 'react';
import '@chatui/core/es/styles/index.less';
// 引入组件
import Chat, { Bubble, useMessages } from '@chatui/core';
// 引入样式
import '@chatui/core/dist/index.css';
渲染界面#
通过 <Chat>
组件渲染出对话界面:
const App = () => {
const { messages, appendMsg, setTyping } = useMessages([]);
function handleSend(type, val) {
if (type === 'text' && val.trim()) {
appendMsg({
type: 'text',
content: { text: val },
position: 'right',
});
setTyping(true);
setTimeout(() => {
appendMsg({
type: 'text',
content: { text: 'Bala bala' },
});
}, 1000);
}
}
function renderMessageContent(msg) {
const { content } = msg;
return <Bubble content={content.text} />;
}
return (
<Chat
navbar={{ title: '智能助理' }}
messages={messages}
renderMessageContent={renderMessageContent}
onSend={handleSend}
/>
);
};
更多参数可查看 Chat 对话容器。
安全区适配#
iPhone X 等机型顶部有刘海、底部有底部指示条,都会存在重合或覆盖的可能,所以我们需要安全区域的适配:
<!-- 添加 meta 标签,并设置 viewport-fit=cover -->
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover"
/>
同时 ChatUI 提供了2个 CSS 变量:--safe-top
、--safe-bottom
,方便使用:
.my-header {
padding-top: var(--safe-top);
}
图标#
ChatUI 图标#
使用图标你需要安装 ChatUI 图标组件包:
<script src="//g.alicdn.com/chatui/icons/2.0.2/index.js"></script>
自定义图标#
或者你也可以通过 SVG Symbol 定义自己的图标,这得注意 Symbol ID 的命名规范 icon-${iconName}
<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
<symbol id="icon-alarm" viewBox="0 0 32 32">
<path d="M16 26c5.523 0 10-4.477 10-10S21.523 6 16 6 6 10.477 6 16s4.477 10 10 10zm6.17.294A11.944 11.944 0 0116 28c-2.223 0-4.304-.604-6.09-1.657l-1.012 1.753a1 1 0 01-1.732-1l1.106-1.915A11.974 11.974 0 014 16C4 9.373 9.373 4 16 4s12 5.373 12 12c0 3.65-1.629 6.918-4.2 9.119l1.066 1.845a1 1 0 01-1.732 1l-.964-1.67zM5.052 8.353a1 1 0 01-1.414-1.415l3.3-3.3a1 1 0 011.414 1.415l-3.3 3.3zm23.323-1.41a1 1 0 11-1.415 1.414l-3.3-3.3a1 1 0 011.415-1.414l3.3 3.3zM16.667 16V9.667a1 1 0 00-2 0V17a1 1 0 001 1h6a1 1 0 000-2h-5z">
</symbol>
</svg>