[英]How to change a component state when i click on a button that is on another component
[英]How do we change the state of element in a react component on button click in another component?
我想在componentOne
中的元素上添加活动 class 上的按钮单击componentTwo
。 我正在使用 useState 但我不知道如何将 state 传递给另一个组件。 componentTwo
是componentOne
的子级。
我想要活动的 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.