[英]Add to favourites and view from favourites with React Hooks?
I have a state我有一个 state
const [ideas, setIdeas] = useState([{title:"test", favourite:false]);
Component Idea.jsx
returns props.title
and a button "fav" .组件
Idea.jsx
返回props.title
和一个按钮"fav" 。
App.jsx
maps through the idea[]
and renders each idea.title
in App.jsx
通过idea[]
映射并渲染每个idea.title
<Item title = {idea.title}/>
on the page.在页面上。
Problem: Every time when "fav" is clicked I want to toggle ideas[index].favourite
.问题:每次单击“fav”时,我都想切换
ideas[index].favourite
。 How to change a value of favourite
only for an idea
that was clicked?如何仅为点击的
idea
更改favourite
值?
How to add this exact idea
to the array favourites[]
?如何将这个确切的
idea
添加到数组favourites[]
中?
App.jsx应用程序.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项目.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}/>
In item component you have to handle click with handleFavToggle and pass all params在项目组件中,您必须使用 handleFavToggle 处理单击并传递所有参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.