[英]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.