简体   繁体   English

单击 div 外部

[英]Click outside of the div

Have an issue for you.有一个问题给你。

I'm making a React App and want to implement one feature我正在制作一个 React 应用程序并想要实现一个功能

Imagine we have a 'X' icon.想象一下,我们有一个“X”图标。 When we click on it div emerges BUT after we click in any place outside of the div it becomes hidden again.当我们单击它时,div 会出现,但是在我们单击 div 之外的任何位置后,它会再次隐藏。

How to create such function?如何创建这样的 function?

use window.onclick event to hide it, note that you have to check the event.target is not your div or one of it child.使用 window.onclick 事件来隐藏它,请注意,您必须检查 event.target 不是您的 div 或它的一个孩子。

for react create state on your root component, change it on onclick and walk down it target child.为了反应在你的根组件上创建 state,在 onclick 上更改它并沿着它向下走目标子组件。 like this:像这样:

class MyApp extends React.Component{
   constructor(props){
      super(props)
     this.state = {
       DivVisible:false,
     }
   }

 CloseDiv(){
    this.setState({DivVisible : false})
}

OpenDiv(){
    this.setState({DivVisible : true})
}

setDivVisible(v){
    if(v)
        this.OpenDiv()
    else 
        this.CloseDiv()
}

render(){
    return <div onClick={() => {this.CloseDiv()}}>

        <MyComponent DivVisible={this.state.DivVisible}  
                setDivVisible={(v) => { setTimeout(()=>{this.setDivVisible(v)}, 100) } } 
                index={this.state.pageIndex}
                goto={(i)=>this.goto(i)} />

    </div>
    
 }
}//end class

let the state DivVisible and the function setDivVisible walk down to child of MyComponent until you reach to target child then set the css style like this:让 state DivVisible 和 function setDivVisible 走到 MyComponent 的孩子,直到到达目标孩子,然后设置 css 样式

  <MyChild  style={{display:props.DivVisible? 'block':'none'}} onclick={)(()=>props.setDivVisiable(true)} />

Here is a very crude version: https://codesandbox.io/s/elated-wilbur-wn8e6?file=/src/App.js:0-844这是一个非常粗略的版本: https://codesandbox.io/s/elated-wilbur-wn8e6?file=/src/App.js:0-844

import React from "react";
import "./styles.css";

export default function App() {
  const [show_div, setShowDiv] = React.useState(false);

  React.useEffect(() => {
    window.addEventListener("click", function (event) {
      if (event.target.id !== "mydiv" && event.target.id !== "clicker") {
        setShowDiv(false);
      }
    });
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <a href="#" id="clicker" onClick={() => setShowDiv(!show_div)}>
        X
      </a>

      {show_div ? (
        <div id="mydiv" className="dima">
          This Div is showing
        </div>
      ) : null}
    </div>
  );
}

Obviously this is not a production example, but it will get you started.显然这不是一个生产示例,但它会让你开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM