【问题标题】:Material UI Drawer not Opening even if state is True即使状态为 True,Material UI Drawer 也不会打开
【发布时间】:2020-05-21 15:52:24
【问题描述】:

我正在使用 ReactMaterial UI 构建一个 WebApp。我遵循了一些关于 Drawer 和文档的教程,但我似乎不明白它是如何工作的。

即使我的 Drawer 打开状态是 True,即使在初始化时它仍然没有打开。

我似乎没有找到我错的地方。

这是标题的代码:

import React from 'react';
import clsx from 'clsx';
import {List, ListItem, ListItemIcon, ListItemText} from '@material-ui/core'

import { ContactsIcon } from '@material-ui/icons/Contacts'
import { HomeIcon } from '@material-ui/icons/Home'
import { GroupIcon } from '@material-ui/icons/Group'
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import Drawer from '@material-ui/core/Drawer'

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  title: {
    flexGrow: 1,
  },
  list: {
      width: 250,
  },
  fullList: {
      width: 'auto',
  },
}));


function indexToIcon(index) {
    if(index === 0){
        return <HomeIcon/>
    }
    else if(index === 1){
        return <GroupIcon/>
    }
    else if(index === 2){
        return <ContactsIcon/>
    }
}

export default function ButtonAppBar() {
    const classes = useStyles();

    const [state, setState] = React.useState({
        left:false,
    });

    const toggleDrawer = (open) => (event) => {
        if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')){
            return;
        }
        setState({ ...state, left: open });
    };

  const list = left => (
      <div>
          <List>
              {['Start', 'Über uns', 'Kontakt'].map((text, index) => (
                  <ListItem button key={text}>
                      <ListItemIcon>{indexToIcon(index)} </ListItemIcon>
                      <ListItemText primary={text} />
                  </ListItem>
              ))}
          </List>
      </div>
  );


  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton onClick={toggleDrawer(true)} edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
            <MenuIcon></MenuIcon>
          </IconButton>
          <Drawer open={true} onClose={toggleDrawer(false)}>
            {list}
          </Drawer>
          <Typography variant="h6" className={classes.title}>
            News
          </Typography>
          <Button color="inherit">Login</Button>
        </Toolbar>
      </AppBar>
    </div>
  )};

那是我的 app.js:

import React from 'react';
import './App.css';
import { Button, Typography, Grid } from '@material-ui/core';
import Header from "./Header"

export default function App() {
  return(
    <div className="App">
      <Grid direction="column">

        <Header></Header>
        <Grid item xs={2}></Grid>
        <Grid item xs={8}>
        a Scur   a Scur   a Scur   a Scur   a Scur   a Scur   a Scur   a Scur   a Scur
        </Grid>
        <Grid item xs={2}></Grid>



      </Grid>
    </div>
  );
  }

以及我对 package.json 的依赖:

    {
      "name": "my-app",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@material-ui/core": "^4.9.14",
        "@material-ui/icons": "^4.9.1",
        "@testing-library/jest-dom": "^4.2.4",
        "@testing-library/react": "^9.5.0",
        "@testing-library/user-event": "^7.2.1",
        "react": "^16.13.1",
        "react-dom": "^16.13.1",
        "react-scripts": "3.4.1"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
      "eslintConfig": {
        "extends": "react-app"
      },
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }

【问题讨论】:

    标签: javascript reactjs visual-studio-code material-ui


    【解决方案1】:

    语法错误:

    <Drawer>, open={true} onClose={toggleDrawer(false)}>
    

    应该是

    <Drawer open={true} onClose={toggleDrawer(false)} >
    

    【讨论】:

      【解决方案2】:

      您的 Drawer 子项内容似乎未呈现,因为您没有调用 list 函数。这就是为什么你看不到它。试试这个:

      <Drawer open={state.left} onClose={toggleDrawer(false)}>
        {list()}
      </Drawer>
      

      另外请记住,不建议在 React 组件中定义函数,因为它可能会影响性能:这些函数会在每个渲染周期重新创建。您应该使用 useCallback 挂钩来记忆函数,例如:

      const renderList = useCallback((left) => (
        <div>
          <List>
            {['Start', 'Über uns', 'Kontakt'].map((text, index) => (
              <ListItem button key={text}>
                <ListItemIcon>{indexToIcon(index)}</ListItemIcon>
                <ListItemText primary={text} />
              </ListItem>
            ))}
          </List>
        </div>
      ), []);
      

      【讨论】:

      • 嘿,我已经使用了你的两个技巧,它仍然很好,没有打开。如果你介意的话,我已经将我的代码部署到 CodeSandbox .. codesandbox.io/s/n3zlw
      • @NicoWalsemann 您还必须将 state.left 传递给 Drawer 的 open 道具。我更新了我的答案,但您也可以查看分叉示例:codesandbox.io/s/my-app-3pec4
      猜你喜欢
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 2018-11-16
      • 1970-01-01
      • 2021-12-20
      • 2017-09-22
      相关资源
      最近更新 更多