简体   繁体   中英

Update Parent State from Child Component and send back response to child

I have two components,

Component A -

const handleLike(id) {
.....
handle the logic for the button and setting the state
}

<ComponentB handleLike={handleLike}/>

Component 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

How can this be solved?

Component 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 -

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:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM