当在chide中调用onClick
时,在父级调用useState()
的自动调用useState()
我想关闭div
,但我不能,最终它将始终在父级调用onClick
,然后总是“打开”
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const Message = () => {
const [message, setMessage] = useState("");
const click = () => {
console.log("open");
setMessage("open");
};
const close = () => {
console.log("close");
setMessage("close");
};
return (
<div>
<div onClick={() => click()}>
{message === "open" ? (
<div>
open
<button onClick={() => close()}>close na</button>
</div>
) : (
<div>not open</div>
)}
</div>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Message />, rootElement);
答案 0 :(得分:0)
您需要停止事件冒泡。如下修改您的代码。
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const Message = () => {
const [message, setMessage] = useState("");
const click = () => {
console.log("open");
setMessage("open");
};
const close = (e) => {
e.stopPropagation(); // Stop this click event to trigger click on parent onClick()
console.log("close");
setMessage("close");
};
return (
<div>
<div onClick={() => click()}>
{message === "open" ? (
<div>
open
<button onClick={(e) => close(e)}>close na</button> // pass event or use onClick={close}
</div>
) : (
<div>not open</div>
)}
</div>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Message />, rootElement);
有关冒泡和捕获的更多信息,请阅读Event bubbling and capturing。