有没有办法检查和取消选中“复选框”?从我的例子? [英] is there way to check and unchecked the "check-boxes" from my example?

查看:85
本文介绍了有没有办法检查和取消选中“复选框”?从我的例子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的示例,我尝试检查并取消选中复选框,但是我很困惑,如果有人向我展示应该怎么做,我会很高兴。

this is my example that I try to check and unchecked the "check-boxes" but I get confused and i will be happy if someone shows me how it should be done.

import React, { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { CheckBox } from 'react-native-elements';

const NewPlaceScreen = props => {
 const [checked, setChecked] = useState(false);


 return (
     <View>
         <CheckBox
             iconRight
             right
             title="apple"
             checked={checked}
             onPress={() => setChecked(true)}
         />
         <CheckBox
             iconRight
             right
             title="kiwi"
             checked={checked}
             onPress={() => setChecked(true)}
         />
     </View>
 );

};

NewPlaceScreen.navigationOptions = {
 headerTitle: 'viewsqq'
};

const styles = StyleSheet.create({
 TextStyle: {
     fontWeight: 'bold',
     color: 'grey'

 }
});

export default NewPlaceScreen

以上就是我的示例

推荐答案

按下时,需要将它们设置为与先前状态相反的状态。您可以使用setState回调做到这一点:

You need to set them to the opposite of their previous state when pressed. You can do this by using the setState callback:

onPress={() => setChecked(prev => !prev)}

目前,您的复选框都使用相同的状态变量已选中,以便它们保持同步-更改一个将更改另一个。如果这不是您想要的,则应为每个复选框创建一个单独的状态变量。

At the moment your check boxes are both using the same state variable checked so they will stay in sync - changing one will change the other. If this is not what you want, you should create a separate state variable for each checkbox.

更新:

要独立处理每个复选框,您需要为每个复选框创建状态:

To treat each checkbox independently, you need to create state for each checkbox:

const [isAppleChecked, setIsAppleChecked] = useState(false)
const [isKiwiChecked, setIsKiwiChecked] = useState(false)

return (
  <View>
    <CheckBox
      iconRight
      right
      title="apple"
      checked={isAppleChecked}
      onPress={() => setIsAppleChecked(prev => !prev)}
    />
    <CheckBox
      iconRight
      right
      title="kiwi"
      checked={isKiwiChecked}
      onPress={() => setIsKiwiChecked(prev => !prev)}
    />
  </View>
)

这篇关于有没有办法检查和取消选中“复选框”?从我的例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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