[英]Update Parent State from Child Component and send back response to child
I have two components,我有两个组件,
Component A -组分 A -
const handleLike(id) {
.....
handle the logic for the button and setting the state
}
<ComponentB handleLike={handleLike}/>
Component B -组分 B -
return(
<>
<button onclick={props.handleLike("123")}/>
</>
)
<ComponentB handleLike={handleLike}/>
This code works, but it changes the state in the Component A and the state is not updated in the Component B此代码有效,但它更改了组件 A 中的状态,并且组件 B 中的状态未更新
How can this be solved?如何解决?
Component A -组分 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}/>
Component B -组分 B -
const { likeId }=props
return(
<>
<button onclick={props.handleLike("123")}/>
</>
)
You can use useState in your parent component, handle callback from child, update the state, and pass the state to child component like this:您可以在父组件中使用 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.