简体   繁体   English

反应。 如何在 .map 方法之后仅将状态更改为当前元素?

[英]React. How to change state only to current element after .map method?

When all list items are rendered I want that after click only clicked list item has been changed its style.当呈现所有列表项时,我希望单击后仅单击的列表项已更改其样式。

const [currentStyle, setCurrentStyle] = useState();

array.map(val => (<li style={currentStyle}>{val.name}</li>)

I advise you to make another component for you items, that way it will be easier to manage state for each item我建议您为您的项目制作另一个组件,这样可以更轻松地管理每个项目的状态

for instance :例如 :

function YourComponent() {    
...
const [currentStyle, setCurrentStyle] = useState();
    ...
    array.map(val => (<ItemComponent style={currentStyle}>{val.name}</ItemComponent>)
...
}

function ItemComponent({style, children}) {
   const [changeStyle, setChangeStyle] = useState(false)
   return (
       <li onClick={() => {setChangeStyle(true)}} style={changeStyle ? style : null}>{children}</li>
    )
}

The better way to do that has already been shared by Jimmy. Jimmy 已经分享了更好的方法。 but if you are lazy you can do something like.但如果你很懒,你可以做类似的事情。

Note: Both approaches are different.注意:两种方法是不同的。 If you manage that via subcomponents you will have to add extra logic to keep track of clicked items in the parent.如果您通过子组件管理它,您将必须添加额外的逻辑来跟踪父级中单击的项目。 (Still recommended) (还是推荐)

But if you use this one you can have the clicked Items track in the component itself (clickedItems)但是如果你使用这个,你可以在组件本身(clickedItems)中跟踪点击的项目

const [currentStyle, setCurrentStyle] = useState();
const [clickedItems, setClickedItems] = useState([]);

array.map((val, index) => (<li onClick={() => 
    setClickedItems(clickedItems.find(i => i===index) ? clickedItems : [...clickedItems, index])}
    style={clickedItems.find(i => i===index) ? currentStyle : null}>{val.name}
</li>)

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

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