我有一个状态
const [ideas, setIdeas] = useState([{title:"test", favourite:false]);
组件CCD_ 1返回CCD_;fav"。
App.jsx
映射通过idea[]
并在中渲染每个idea.title
<Item title = {idea.title}/>
在页面上。
问题:每次"fav">,我想切换ideas[index].favourite
。如何仅为单击的idea
更改favourite
的值?
如何将这个精确的idea
添加到数组Idea.jsx
0中?
应用程序.jsx
function App() {
const [ideas, setIdeas] = useState([{title:"test",
favourite:false}]);
const [isClicked, setIsClicked] = useState(false)
function showAllIdeas () {
setIsClicked(prevValue => {
return !prevValue
}
)
}
function mapIdeas(){return ideas.map((ideaItem, index) => {
return (<Idea
key = {index}
id = {index}
title = {ideaItem.title}
/>
);
})}
return ( <div>
<Fab color="primary" onClick={showAllIdeas}>{expandText()}</Fab>
{isClicked && mapIdeas()}
</div>)
}
Item.jsx
function Idea(props) {
const [isClicked, setIsClicked] = useState(false)
function handleClick(){
setIsClicked(prevValue => {
return !prevValue
})
}
console.log(isClicked)
return(
<div className={"idea-list" } ><p>{props.title} {isClicked ?
<StarIcon onClick={handleClick}/> :<StarBorderIcon onClick=.
{handleClick}/>}</p>
</div>
)
}
const handleFavToggle = (index) => {
setItems(items=> {
const data = [...items]
data[index] = {...data[index],favourite: !data[index].favourite }
return data
})
}
<Item key={index} title={item.title} index={index} handleFavToggle={handleFavToggle}/>
在项目组件中,您必须使用handleFavToggle处理点击并传递所有参数