Javascript 如何在外部单击时关闭div部分?
我有搜索建议部分,当用户开始搜索时打开 这意味着,当用户在搜索输入中键入内容时,我调用Javascript 如何在外部单击时关闭div部分?,javascript,html,reactjs,Javascript,Html,Reactjs,我有搜索建议部分,当用户开始搜索时打开 这意味着,当用户在搜索输入中键入内容时,我调用setState({isSearchActive:true}) 现在,当用户在搜索建议div部分之外单击时,我想调用`setState({isSearchActive:false})`` 在父组件中,我创建了函数handleClosingSuggestions(): 为什么不触发模糊事件而不更改状态?在SuggestionList组件中,您可以像这样添加/删除事件侦听器 componentDidMount()
setState({isSearchActive:true})
现在,当用户在搜索建议
div部分之外单击时,我想调用`setState({isSearchActive:false})``
在父组件中,我创建了函数handleClosingSuggestions()
:
为什么不触发模糊事件而不更改状态?在
SuggestionList
组件中,您可以像这样添加/删除事件侦听器
componentDidMount() {
document.addEventListener('click', this.handleClosingSuggestions);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClosingSuggestions);
}
export default ({ suggestionsArray, handleClosingSuggestions }) => (
// HERE IS ON BLUR EVENT
<div className="wrapper" onBlur={handleClosingSuggestions}>
<div className="suggestions">
<div className="suggestions-section">
<SuggestionsList suggestionsArray={suggestionsArray} />
</div>
<div className="latest-news-section">
<LatestNewsList image={testImg} text="McLeish exits as Scotland coach after 12 games" />
</div>
<div className="related-trends-section">
<RelatedTrendsList
title="Topics"
option1="Football"
option2="Tennis"
iconClass="icon-arrow-up-right2"
/>
</div>
</div>
</div>
);
componentDidMount() {
document.addEventListener('click', this.handleClosingSuggestions);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClosingSuggestions);
}