ReactJS:图像有时不会出现在按钮点击上

ReactJS: Images are sometimes not appearing on button click

我是 React 菜鸟。我正在使用 Material UI 和 Material UI icons 以及 React 创建带有前进和后退按钮的标题,以便用户可以滚动浏览显示的图片。当我按下前进按钮时,“索引 2”中的图片什么也没有显示。当我按下后退按钮时,“索引 0”中的图片是空白的(很奇怪,对吧?)。在我看来,这似乎是一个超级奇怪的错误。我在这里缺少什么吗?这对我来说毫无意义。

这是我的代码(如您所见,我仍在编辑内容,所以我仍然拥有从 Material UI 抓取此代码时的默认文本)。

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import CardActions from '@material-ui/core/CardActions';
import Collapse from '@material-ui/core/Collapse';
import Avatar from '@material-ui/core/Avatar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import { red } from '@material-ui/core/colors';
import FavoriteIcon from '@material-ui/icons/Favorite';
import ShareIcon from '@material-ui/icons/Share';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import ArrowForwardIosIcon from '@material-ui/icons/ArrowForwardIos';
import ArrowBackIosIcon from '@material-ui/icons/ArrowBackIos';

import image2019_0201 from '../images/2019_0201.jpeg';
import image2019_0202 from '../images/2019_0202.jpeg';
import image2019_0203 from '../images/2019_0203.jpeg';

const images = [
    image2019_0201,
    image2019_0202,
    image2019_0203,
];

const imageText = [
    "February 15, 2019",
    "text2",
    "text3"
]

const useStyles = makeStyles((theme) => ({
  root: {
    maxWidth: 345,
  },
  media: {
    height: 0,
    paddingTop: '56.25%', // 16:9
  },
  expand: {
    transform: 'rotate(0deg)',
    marginLeft: 'auto',
    transition: theme.transitions.create('transform', {
      duration: theme.transitions.duration.shortest,
    }),
  },
  expandOpen: {
    transform: 'rotate(180deg)',
  },
  avatar: {
    backgroundColor: red[500],
  },
}));

export default function Year2019() {
  const classes = useStyles();
  const [expanded, setExpanded] = React.useState(false);
  const [currentImageIndex, setCurrentImageIndex] = React.useState(0)

  const handleExpandClick = () => {
    setExpanded(!expanded);
  };

  const handleForwardClick = () => {
    console.log("current index", currentImageIndex);
    if (currentImageIndex < images.length) {
      setCurrentImageIndex(currentImageIndex + 1);
    }
    else {
      setCurrentImageIndex(0);
    }
    console.log("new index", currentImageIndex);
  }

  const handleBackClick = () => {
    console.log("current index", currentImageIndex);
    if (currentImageIndex == 0) {
      setCurrentImageIndex(images.length);
    }
    else {
      setCurrentImageIndex(currentImageIndex - 1);
    }
    console.log("new index", currentImageIndex);

  }

  return (
    <Card className={classes.root}>
      <CardHeader
        title="Title"
        subheader="February 15, 2019"
      />
      <CardMedia
        className={classes.media}
        image={images[currentImageIndex]}
        title="image2019_0201"
      />
      <CardContent>
        <Typography variant="body2" color="textSecondary" component="p">
          Waiting for the shuttle.
        </Typography>
      </CardContent>
      <CardActions disableSpacing>
        <IconButton aria-label="back" onClick={handleBackClick}>
          <ArrowBackIosIcon/>
        </IconButton>
        <IconButton aria-label="forward" onClick={handleForwardClick}>
        <ArrowForwardIosIcon/>
        </IconButton>
        <IconButton
          className={clsx(classes.expand, {
            [classes.expandOpen]: expanded,
          })}
          onClick={handleExpandClick}
          aria-expanded={expanded}
          aria-label="show more"
        >
          <ExpandMoreIcon />
        </IconButton>
      </CardActions>
      <Collapse in={expanded} timeout="auto" unmountOnExit>
        <CardContent>
          <Typography paragraph>Method:</Typography>
          <Typography paragraph>
            Heat 1/2 cup of the broth in a pot until simmering, add saffron and set aside for 10
            minutes.
          </Typography>
          <Typography paragraph>
            Heat oil in a (14- to 16-inch) paella pan or a large, deep skillet over medium-high
            heat. Add chicken, shrimp and chorizo, and cook, stirring occasionally until lightly
            browned, 6 to 8 minutes. Transfer shrimp to a large plate and set aside, leaving chicken
            and chorizo in the pan. Add pimentón, bay leaves, garlic, tomatoes, onion, salt and
            pepper, and cook, stirring often until thickened and fragrant, about 10 minutes. Add
            saffron broth and remaining 4 1/2 cups chicken broth; bring to a boil.
          </Typography>
          <Typography paragraph>
            Add rice and stir very gently to distribute. Top with artichokes and peppers, and cook
            without stirring, until most of the liquid is absorbed, 15 to 18 minutes. Reduce heat to
            medium-low, add reserved shrimp and mussels, tucking them down into the rice, and cook
            again without stirring, until mussels have opened and rice is just tender, 5 to 7
            minutes more. (Discard any mussels that don’t open.)
          </Typography>
          <Typography>
            Set aside off of the heat to let rest for 10 minutes, and then serve.
          </Typography>
        </CardContent>
      </Collapse>
    </Card>
  );
}

Picture of the Forward and Backward Icons

在您的处理程序函数中,数组索引可能超出范围。所以你应该像下面这样修改你的处理函数:

const handleForwardClick = () => {
  if (currentImageIndex < (images.length - 1)) {
    setCurrentImageIndex(currentImageIndex + 1);
  }
  else {
    setCurrentImageIndex(0);
  }
}

const handleBackClick = () => {
  if (currentImageIndex == 0) {
    setCurrentImageIndex(images.length - 1);
  }
  else {
    setCurrentImageIndex(currentImageIndex - 1);
  }
}