使用状态不适用于之后的组件

usestate not working for afterwards components

但是即使我点击了最后三张卡片中的评级星,所有的变化都发生在第一张卡片上,我不知道why.I我不确定是什么问题is.Can你解释一下?我不仅做了一个简单的展示完成了什么,我想知道为什么,谢谢。 这是我的代码:

import React from "react";
import { useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import Grid from "@material-ui/core/Grid";
import DeleteIcon from "@material-ui/icons/Delete";
import Box from "@material-ui/core/Box";
import Typography from "@material-ui/core/Typography";
import Rating from "@material-ui/lab/Rating";

const useStyles = makeStyles({
  title: {
    fontSize: 20,
    textAlign: "center"
  }
});

export default function ColorCard({ title, color, rating, timestamp }) {
  const classes = useStyles();
  const [value, setValue] = useState(rating);

  return (
    <Grid item>
      <Card>
        <Typography className={classes.title}>
          {title}
          <DeleteIcon
            style={{
              float: "right"
            }}
          />
        </Typography>

        <Box
          style={{
            backgroundColor: `${color}`,
            padding: "10%",
            margin: "5%"
          }}
        ></Box>
        <Rating
          name="simple-controlled"
          value={value}
          onChange={(event, newValue) => {
            setValue(newValue);
          }}
        />
        <Typography
          component="legend"
          style={{
            fontSize: "2vw"
          }}
        >
          {value} of 5 stars
          <span
            style={{
              float: "right"
            }}
          >
            {timestamp}
          </span>
        </Typography>
      </Card>
    </Grid>
  );
}

完整项目:https://codesandbox.io/s/material-demo-forked-62eh0?file=/ColorCard.js:201-253

问题是由 <Rating name="simple-controlled" 引起的。 Rating 由视觉上隐藏的无线电输入支持,以提供可访问性方面(例如键盘功能)。无线电输入的 name 属性 由传递给 Ratingname 属性 控制,因此您需要为每个等级指定一个唯一的名称。

这是您的沙箱的修改版本,演示了这一点:https://codesandbox.io/s/material-demo-forked-kytd5?file=/ColorCards.js:365-389

更改涉及将 inputName 道具传递给 ColorCard:

<ColorCard key={color.id} inputName={`ratingFor${color.id}`} ...

然后在渲染 Rating:

时使用它
<Rating name={inputName} ...

来自 Rating 文档的 Accessibility 部分:

The accessibility of this component relies on:

  • A radio group is used with its fields visually hidden. It contains six radio buttons, one for each star and another for 0 stars, which is checked by default. Make sure you are providing a name prop that is unique to the parent form.