0

我在 React 中有一个模态。当您单击模态框的背景时,模态框应该关闭。我现在设置它的方式,如果你点击里面*模式,它也会关闭。因为模态在背景里面>

handleClose(e) {
    e.stopPropagation(); 
    this.props.history.push('/business/dashboard') 
  }

  render() {
    return (
      <Background onClick={e => this.handleClose(e)} name="BACKGROUND">
        <Container onClick={console.log("IT CLICKED")} to={'/business/dashboard'} name="CONTAINER">
             ....

当我单击 Container 时,会调用 Background 的 onClick 事件。我不希望这种情况发生。这是用户将一直点击的表单。我只需要在您单击背景上的模态外部时关闭模态。

4

2 回答 2

2

我认为如果您stopPropagationContainerclick 事件上使用而不是在Background. 只需确保在组件中使用该onClick道具。Container

class App extends React.Component {
  handleClose = (e) => {
    e.stopPropagation();
    this.props.history.push("/business/dashboard");
  };

  render() {
    return (
      <Background onClick={this.handleClose} name="BACKGROUND">
        <Container
          onClick={e => e.stopPropagation()}
          to={"/business/dashboard"}
          name="CONTAINER"
        />
      </Background>
    );
  }
}
于 2018-06-29T22:02:41.657 回答
0

编辑:在重新阅读问题时,在这种情况下,另一个答案是一个更简单的解决方案。

您想要实现的行为通常称为“外部点击”处理程序。有几个不错的库可以处理这个 [0],如果您想详细了解它的工作原理,它们的源代码非常简短且易读。[1]

一般的想法是在 HOC 中的文档上注册一个 click 事件处理程序,并通过浏览器功能检查是否event.target源自 React 内部。如果是,则不会执行处理程序。refElement.contains

[0] https://github.com/tj/react-click-outside

[1] https://github.com/tj/react-click-outside/blob/master/index.js

于 2018-06-29T21:57:45.497 回答