【问题标题】:useEffect equivalent in a class component类组件中的 useEffect 等价物
【发布时间】:2022-11-25 11:10:25
【问题描述】:

我想在单击它时关闭一个组件并使用以下代码。

这个 useEffect 在类组件中看起来如何?

useEffect(() => {
  document.addEventListener('mousedown', (event) => {
    if (!panelRef.current?.contains(event.target)) {
      console.log('hello')
    }
  })
})

【问题讨论】:

  • 可能this就是你要找的

标签: javascript reactjs react-hooks


【解决方案1】:

你可以使用componentDidMount,但我建议你也应该使用componentWillUnmount来清理你的鼠标事件。

class YourComponent extends React.Component {
  mouseDown(event) {
    if (!panelRef.current?.contains(event.target)) {
      console.log("hello");
    }
  }

  componentDidMount() {
    document.addEventListener("mousedown", this.mouseDown);
  }

  componentWillUnmount() {
    document.removeEventListener("mousedown", this.mouseDown);
  }

  render() {
    return <h1>Your JSX</h1>;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-22
    • 2021-12-21
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    相关资源
    最近更新 更多