How to integrate constants and functions in React Component class?
让我们从Material-UI中获取AppBar代码:
https://material-ui.com/components/app-bar/#app-bar-with-a-primary-search-field
有一个" renderMobileMenu"。我想整合它。问题在于示例代码使用"函数",而我的是React Component类。我需要有关如何在React Component类中集成renderMobileMenu(和相关)代码的指南。
我也在使用React Redux。
1 2 3 4 | export default connect( mapStateToProps, {wbToggle: wbToggle, vidToggle: vidToggle, fileToggle: fileToggle} )(Utilitybar); |
我已经尝试过,但始终会给出错误,表明我违反了钩子定律。
我假设您的班级名称是" Utilitybar"。由于需要使用示例中的代码和功能,可以通过两种方式实现它,
只需复制所需的函数,然后将其粘贴到具有必需的依赖函数和程序包的类之外,然后将其调用-(不建议使用的方法和肮脏的方式)
使用需要在现有类中添加它的功能来创建一个无状态组件(根据您的状态为全状态/无状态),在新创建的无状态组件中导入所需的功能和包。完成后,您的无状态组件就可以使用了,然后继续导入您的Utilitybar并使用它。
请参考以下示例,
您需要创建一个单独的无状态组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | <path>/MobileMenu.js /*import the dependency packages, files you are referring in your sample function*/ import React from 'react'; import { fade, makeStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; ... ... .... export const RenderMobileMenu = ({ }) => { /*copied the dependent functions to render - renderMobileMenu*/ const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = React.useState(null); const [anchorEl, setAnchorEl] = React.useState(null); const isMenuOpen = Boolean(anchorEl); const isMobileMenuOpen = Boolean(mobileMoreAnchorEl); const mobileMenuId = 'primary-search-account-menu-mobile'; function handleMobileMenuClose() { setMobileMoreAnchorEl(null); } function handleMenuClose() { setAnchorEl(null); handleMobileMenuClose(); } /*copied the code under renderMobileMenu*/ return ( <Menu anchorEl={mobileMoreAnchorEl} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} id={mobileMenuId} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'right' }} open={isMobileMenuOpen} onClose={handleMobileMenuClose} > <MenuItem> <IconButton aria-label="Show 4 new mails" color="inherit"> <Badge badgeContent={4} color="secondary"> <MailIcon /> </Badge> </IconButton> <p><center>[wp_ad_camp_2]</center></p><p>Messages</p> </MenuItem> <MenuItem> <IconButton aria-label="Show 11 new notifications" color="inherit"> <Badge badgeContent={11} color="secondary"> <NotificationsIcon /> </Badge> </IconButton> <p>Notifications</p> </MenuItem> <MenuItem onClick={handleProfileMenuOpen}> <IconButton aria-label="Account of current user" aria-controls="primary-search-account-menu" aria-haspopup="true" color="inherit" > <AccountCircle /> </IconButton> <p>Profile</p> </MenuItem> </Menu> ) } |
现在,RenderMobileMenu已准备好为Utilitybar.js服务。
只需继续,将此RenderMobileMenu.js文件导入到Utilitybar.js中,并在render(return())方法下使用它。
编码愉快!
您可以查看v3文档,以了解它是如何以老式方式使用的。
https://v3.material-ui.com/demos/app-bar/#app-bar