Click on the blank area to hide the component

1. hooks

const [moreList, toggleMoreList] = useState(false)
useEffect(() = > {
  // Bind the click event on document to hide the pop-up layer
  document.addEventListener("click".(e) = > toggleMoreList(false));
}, [])
// Encapsulates the function to prevent bubbles
const stopPropagation = (e) = > {
  e.nativeEvent.stopImmediatePropagation();
}
const onShow = (e) = > {
  / / use the react e.s topPropagation cannot prevent bubble, you need to use e.n ativeEvent. StopImmediatePropagation, here we are on the packaging, convenient multiple callsstopPropagation(e); toggleMoreList(! moreList) }Copy the code
/ / button<button onClick={onShow}>/ / box
<div style={{display:` ${moreList ? 'block' : 'none` '}}} >
  <ul role="menu" tabIndex="1" className="cpJjC _g z">
    <li role="none">
    </li>
  </ul>
</div>
Copy the code

2.class

this.state={
  showInput:false
}
componentDidMount() {
  document.addEventListener('click'.(e) = > {
  this.setState({
    showInput: false,
  })
 })
}

stopPropagation = (e) = > {
  e.nativeEvent.stopImmediatePropagation();
}

onShow = (e) = > {
  console.log(123)
  / / use the react e.s topPropagation cannot prevent bubble, you need to use e.n ativeEvent. StopImmediatePropagation, here we are on the packaging, convenient multiple calls
  this.stopPropagation(e);
  this.setState({
    showInput:!this.state.showInput
  })
}
Copy the code
render() {
  const { showInput } = this.state
  return(
      <>
        <div onClick={(e)= >This.onshow (e)}> Click more</div>
        <div style={{display:` ${showInput ? 'block' : 'none` '}}}) >
    </>
)}
Copy the code