簡體   English   中英

我們如何在另一個組件中單擊按鈕時更改反應組件中元素的 state?

[英]How do we change the state of element in a react component on button click in another component?

我想在componentOne中的元素上添加活動 class 上的按鈕單擊componentTwo 我正在使用 useState 但我不知道如何將 state 傳遞給另一個組件。 componentTwocomponentOne的子級。

我想要活動的 class componentOne只要即使再次加載瀏覽器也不會再次單擊該按鈕

只需在父組件中創建一個 state 並將其作為道具傳遞

cosnt [active , setActive] =useState(false)

<ParentComponent>
    <componentOne active={active} , setActive={setActive} />
     <componentTwo active={active} , setActive={setActive} />
</ParentCompnent>

Component One :

  const ComponentOne = ({active}) => {
  return(
        <div className={`${active && 'activeClass'}`}></div>
   )  
 }


Component Two :

  const  ComponentTwo = ({setActive}) => {
  return(
        <button onClick={()=> setActive(true)}>
   )  
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM