[英]Prevent onClick getting fired on load. I'm using the functional component on a React project
This is the Parent Component which passes a reference to the cart component这是传递对购物车组件的引用的父组件
function Header() {
const cartRef = useRef();
const handleClick = () =>{
cartRef.current.style.boxShadow = "0 0 0 100vw rgb(0, 0, 0, 0.9)"
}
return (
<>
<Cart cRef={cartRef} onClick={()=>{handleClick()}}/>
</>
);
}
export default Header;
The Child Component assigns the reference to the div shown below子组件将引用分配给如下所示的 div
function Cart(props) {
return (<>
<div ref={props.cRef}>
...
</div>
</>
);
}
export default Cart;
Does passing references like this cause such issues?像这样传递引用会导致此类问题吗?
Try it like this: <Cart cRef={cartRef} onClick={handleClick}/>
试试这样:
<Cart cRef={cartRef} onClick={handleClick}/>
I think the handleClick
fires because it's passed in a wrong way.我认为
handleClick
触发是因为它以错误的方式传递。
The handleClick() isn't actually getting fired. handleClick() 实际上并没有被解雇。 Whats happening is that the Cart component that has been imported to the Header component will be visible like any component does when placed in the return statement.
发生的情况是,已导入到 Header 组件的 Cart 组件将像放置在 return 语句中的任何组件一样可见。
function Header() {
const cartRef = useRef();
const handleClick = () =>{
cartRef.current.style.visibility = "visible";
cartRef.current.style.boxShadow = "0 0 0 100vw rgb(0, 0, 0, 0.9)"
}
return (
<>
<Cart cRef={cartRef} onClick={()=>{handleClick()}}/>
</>
);
}
export default Header;
We can set the Cart component's Visibility to 'hidden' and then on the handleClick() event handler, we set it back to 'visible' again.我们可以将 Cart 组件的Visibility设置为“隐藏” ,然后在 handleClick() 事件处理程序上,我们再次将其设置回“可见” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.