通过<div>内的onClick调用useState进行调用时,也会调用userState。为什么最后在主<div>处调用useState?

时间:2019-09-02 16:59:37

标签: javascript reactjs

当在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);

1 个答案:

答案 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