在 React 中单击组件外部时更改状态

Change the state when clicking outside a component in React(在 React 中单击组件外部时更改状态)
本文介绍了在 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 中单击组件外部时更改状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)