本文介绍了在 React 中单击组件外部时更改状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个下拉菜单,如下图所示:
I have a dropdown as is shown in the following image:
当我单击文件夹图标时,它会打开和关闭,因为 showingProjectSelector
属性处于设置为 false 的状态.
When I click the folder icon it opens and closes because showingProjectSelector
property in the state that is set to false.
constructor (props) {
super(props)
const { organization, owner, ownerAvatar } = props
this.state = {
owner,
ownerAvatar,
showingProjectSelector: false
}
}
当我单击该图标时,它会正确打开和关闭.
When I click the icon, it opens and closes properly.
<i
onClick={() => this.setState({ showingProjectSelector: !this.state.showingProjectSelector })}
className='fa fa-folder-open'>
</i>
但是我想要做的是在我点击下拉菜单时关闭它.我如何在不使用任何库的情况下做到这一点?
But what I'm trying to do is to close the dropdown when I click outside it. How can I do this without using any library?
这是整个组件:https://jsbin.com/cunakejufa/edit?js,输出
推荐答案
你可以尝试利用 onBlur
:
<i onClick={...} onBlur={() => this.setState({showingProjectSelector: false})}/>
这篇关于在 React 中单击组件外部时更改状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!