简体   繁体   English

如何在 React 列表 onClick 中更改对象的状态?

[英]How can I change state of object in a React list onClick?

I have a List of Objects looking like this:我有一个看起来像这样的对象列表:

const List = [
  {
    title: " ",
    timestamp: 500,
    seen: false
  },

  {
    title: " ",
    timestamp: 600,
    seen: false
  },

The List ist displayed as a List auf Buttons with a title an an icon.列表显示为带有标题和图标的列表 auf 按钮。 When a Button is clicked, the object should be marked as "seen: true" and the icon should change the color.单击按钮时,应将对象标记为“已看到:true”,并且图标应更改颜色。 My problem: In my chase, the icon only changes the color when the component is rerendert, it should change when the button is clicked though.我的问题:在我的追逐中,图标仅在重新渲染组件时改变颜色,但在单击按钮时它应该改变。 Can someone help?有人可以帮忙吗?


const styles: Styles = {
  icon_unseen: {
    color: "#f97671",
  },
  icon_seen: {
    color: "#bdbdbd",
  }
};

export const  = () => {


  const sortedList = List.sort((a, b) => a.timestamp - b.timestamp);

  const onClick = (event: any) => {
     List.map((item) =>item.timestamp==event.currentTarget.id? item.seen=!item.seen : "")
      };

return (
 <Box>
      <PopperUnstyled>
        <StyledPopperDiv>
          {sortedNList.map((element) => (
            <ListItemButton id={element.timestamp} 
                            onClick={onClick} 
                            sx={{borderRadius: 2}}>
            <ListItem>
            <ListItemText
                  primary={<Typography>{element.title}</Typography>
            />
            <FiberManualRecordRoundedIcon sx={element.seen ? styles.icon_seen : styles.icon_unseen}/>
            </ListItem>
            </ListItemButton>
            <ListItemText
                  primary={<Typography>{element.title}</Typography>
            />
            <FiberManualRecordRoundedIcon sx={element.seen ? styles.icon_seen : styles.icon_unseen}/>

          ))}
        </StyledPopperDiv>
      </PopperUnstyled>
    </Box>
  );
};

I'm not sure where 'List' is coming from but if it would be defined in the component, you need to link it to the component's state.我不确定“列表”来自哪里,但如果它会在组件中定义,则需要将其链接到组件的状态。

const [list, setList] = useState(List);

And when you you want to update it, you do it through setList.而当你想更新它时,你可以通过 setList 来完成。

setList((prevState => ({
    ...prevState, 
    Your changes
}))

This also means that inside the JSX, you use list instead of List. 

Modify these three places to make it work:修改这三个地方使其生效:

// Assume you have fetched data from server and sorted

// Ideally, this should be inside of your data fetching function, not in the component
const sortedList = List.sort((a, b) => a.timestamp - b.timestamp); 

// 1.
const [sortedNList, setSortedNList] = useState(sortedList);

// 2.
const onClick = (timestamp) => { // We don't need to take the event as param here, but timestamp instead
  setSortedNList(sortedNList.map((item) => item.timestamp === timestamp ? {...item, seen: !item.seen} : item))
};

// 3.
{sortedNList.map((element) => (
  <ListItemButton 
    id={element.timestamp} 
    onClick={() => onClick(element.timestamp)} // pass in element's timestamp
    sx={{borderRadius: 2}}>
  ...
)}

Resource recommendation: React Beta docs资源推荐: React Beta 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM