如何切换反应组件的布尔状态? [英] How to toggle boolean state of react component?

查看:39
本文介绍了如何切换反应组件的布尔状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何切换 React 组件的布尔状态.例如:

我在组件的构造函数中进行了布尔状态检查:

constructor(props, context) {超级(道具,上下文);this.state = {检查:假};};

每次单击复选框时,我都尝试使用 this.setState 方法切换状态:

当然,我得到一个未捕获的引用错误:未定义检查.那么我怎样才能做到这一点呢?

非常感谢.

解决方案

由于没有人发布此内容,所以我发布了正确答案.如果您的新状态更新取决于之前的状态,请始终使用 setState 的函数形式,它接受一个返回新状态的函数作为参数.

就你而言:

this.setState(prevState => ({检查: !prevState.check}));

请参阅文档


由于这个答案越来越流行,添加应该用于 React Hooks (v16.8+) 的方法:

如果您使用的是 useState 钩子,然后使用以下代码(以防您的新状态依赖于以前的状态):

const [check, setCheck] = useState(false);//...setCheck(prevCheck => !prevCheck);

I'd like to know how to toggle a boolean state of a react component. For instance:

I have boolean state check in the constructor of my component:

constructor(props, context) { 
   super(props, context);

   this.state = {
      check: false
   };
};

I am trying to toggle the state each time my checkbox is clicked, using the this.setState method:

<label><input type=checkbox" value="check" onChange = {(e) => this.setState({check: !check.value})}/> Checkbox </label>

Of course I get a Uncaught ReferenceError: check is not defined. So how can I achieve this?

Many thanks in advance.

解决方案

Since nobody posted this, I am posting the correct answer. If your new state update depends on the previous state, always use the functional form of setState which accepts as argument a function that returns a new state.

In your case:

this.setState(prevState => ({
  check: !prevState.check
}));

See docs


Since this answer is becoming popular, adding the approach that should be used for React Hooks (v16.8+):

If you are using the useState hook, then use the following code (in case your new state depends on the previous state):

const [check, setCheck] = useState(false);
// ...
setCheck(prevCheck => !prevCheck);

这篇关于如何切换反应组件的布尔状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆