[英]Update Parent State from Child Component and send back response to child
我有兩個組件,
組分 A -
const handleLike(id) {
.....
handle the logic for the button and setting the state
}
<ComponentB handleLike={handleLike}/>
組分 B -
return(
<>
<button onclick={props.handleLike("123")}/>
</>
)
<ComponentB handleLike={handleLike}/>
此代碼有效,但它更改了組件 A 中的狀態,並且組件 B 中的狀態未更新
如何解決?
組分 A -
const[likeId,setLikeId]= useState(like)
const handleLike(id) {
.....
handle the logic for the button and setting the state
setLikeId(id)
}
<ComponentB likeId={likeId} handleLike={handleLike}/>
組分 B -
const { likeId }=props
return(
<>
<button onclick={props.handleLike("123")}/>
</>
)
您可以在父組件中使用 useState,處理來自子組件的回調,更新狀態,並將狀態傳遞給子組件,如下所示:
const ComponentA= () => {
const [likes, setLikes] = useState('')
const handleLikeCallback(id) {
setLikes(id)
}
return <ComponentB handleLikeCallback={handleLikeCallback} likes={likes}/>
}
const ComponentB = ({handleLikeCallback, likes}) =>
<button onclick={handleLikeCallback("123")}>{likes}</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.