reactjs - 无论抽屉是打开还是关闭,如何使 React Material-UI Drawer 的内容运行?
问题描述
我正在构建一个具有聊天功能的 React 应用程序。聊天功能位于Material-UI Drawer中,当单击聊天图标时,该抽屉会切换打开或关闭。
我遇到的问题是每次打开抽屉时聊天应用程序都会启动,并在抽屉关闭时被杀死。因此,每次用户单击聊天图标加入聊天时,他们都会像每次第一次一样加入。
相反,我希望聊天代码运行并保持运行,无论抽屉是打开还是关闭。
这是代码。
import React from 'react';
import './Chat.css';
import Drawer from '@material-ui/core/Drawer';
import ChatIcon from '@material-ui/icons/Chat';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import Tooltip from '@material-ui/core/Tooltip';
import App from './App/App';
import Cookies from 'universal-cookie';
type Anchor = 'right';
// SegmentIO tracking
declare global {
interface Window { analytics: any; }
}
export default function Chat() {
const [state, setState] = React.useState({
right: false,
});
const toggleDrawer = (anchor: Anchor, open: boolean) => (
event: React.KeyboardEvent | React.MouseEvent,
) => {
if (
event.type === 'keydown' &&
((event as React.KeyboardEvent).key === 'Tab' ||
(event as React.KeyboardEvent).key === 'Shift')
) {
return;
}
//SegmentIO Tracking
const cookieMgr = new Cookies();
var identity = cookieMgr.get('identity');
var room = cookieMgr.get('room');
if (open) {
window.analytics.page('Chat');
window.analytics.track('User opened Chat', {
identity: identity,
name: room
});
} else {
window.analytics.track('User closed Chat', {
identity: identity,
name: room
});
}
setState({ ...state, [anchor]: open });
};
return (
<div>
{(['right'] as Anchor[]).map(anchor => (
<React.Fragment key={anchor}>
<Tooltip title="Chat">
<ChatIcon onClick={toggleDrawer(anchor, true)} className="ChatIcon" />
</Tooltip>
<Drawer anchor={anchor} open={state[anchor]} onClose={toggleDrawer(anchor, false)}>
<Card className="rootChat">
<CardContent>
<Typography className="titleChat" gutterBottom>
<div className="titleContainerChat"><ChatIcon fontSize="large" className="titleIconChat" /> Chat</div>
<div className="buttonContainerChat" >
<Tooltip title="Close"><ChevronRightIcon fontSize="large" className="iconCancelChat" onClick={toggleDrawer(anchor, false)} /></Tooltip>
</div>
</Typography>
<App />
</CardContent>
</Card>
</Drawer>
</React.Fragment>
))}
</div>
);
}
这是每次单击聊天图标并打开抽屉时发生的屏幕截图:
解决方案
推荐阅读
- javascript - NoSuchElementError:没有这样的元素:无法找到元素:
- python - 情节背景颜色
- android - 如何在我的 xpath 选择器中为 android.widget.switch 元素合并索引值和检查值?
- codeigniter-3 - 在 codeigniter 中哪里可以看到 Print_r() 的输出
- c - 指向的值指针未更新
- python - Pandas 将两行与正则表达式条件合并
- python - 使用枚举器的奇数
- ios - swift中这个错误的原因是什么?: 脚本错误 -54。由于错误 -1700 无法获取错误文本
- rest - Yammer REST API - 如何从不同来源 (CORS) 获取数据?
- spring - Spring 4 Hikari 连接池 ClassCastException