【问题标题】:How to only select one checkbox in a React Native Android app?如何在 React Native Android 应用程序中只选择一个复选框?
【发布时间】:2022-02-10 16:14:53
【问题描述】:

我正在尝试在 React Native 中设置我的第一个 Android 应用。

现在这张卡片(react-native-component)里面有多个复选框(见下面的代码)。

每次我尝试只选择一个复选框时,它都会以某种方式检查所有复选框。

我知道它与多个状态有关,但我无法让它工作。

我怎样才能只选择一个复选框?

JavaScript 文件:

import React from "react";
import {StyleSheet, ActivityIndicator, ListView, Text, View, Alert, Platform, TouchableOpacity} from 'react-native';
import { Card, CheckBox, Button } from 'react-native-elements';

export default class AgendaItemVote extends React.Component {

    constructor(props) {
        super(props);
        this.state = { checked: false };
    }

    render(){
        return(
            <View style={styles.container}>
                <Card title="Titel Agendapunt">
                    <Text style={styles.paragraph}>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at sapien at tellus interdum finibus. Nunc sagittis tincidunt orci, non viverra ligula feugiat id. Phasellus eleifend massa neque, eu scelerisque enim feugiat ac.
                    </Text>

                    <View style={{flexDirection: 'row'}}>
                        <CheckBox
                            title='Ja'
                            checked={this.state.checked}
                            onPress={() => this.setState({
                                checked: !this.state.checked
                            })}
                        />
                         <CheckBox
                            title='Nee'
                            checked={this.state.checked}
                            onPress={() => this.setState({
                                checked: !this.state.checked
                            })}
                        />
                         <CheckBox
                            title='Onthouding'
                            checked={this.state.checked}
                            onPress={() => this.setState({
                                checked: !this.state.checked
                            })}
                        />

                    </View>
                    <View>
                        <Button
                            title="Indienen"
                        />
                    </View>
                </Card>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      paddingTop: 40,
      backgroundColor: '#ecf0f1',
    },
    paragraph: {
      margin: 24,
      fontSize: 18,
      fontWeight: 'bold',
      textAlign: 'center',
      color: '#34495e',
    },
});

【问题讨论】:

    标签: javascript reactjs react-native checkbox react-native-component


    【解决方案1】:

    我遇到了类似的问题,在解决了这个问题后,我在这里写下我的答案。

    考虑下面的例子 - (带有钩子)

    const checkboxComponent = () => {
    
      const [checkboxValue, setCheckboxValue] = React.useState([
       { label: 'Customer', value: 'customer', checked: false },
       { label: 'Merchant', value: 'merchant', checked: false },
       { label: 'None', value: 'none', checked: false },
     ])
    
     const checkboxHandler = (value, index) => {
       const newValue = checkboxValue.map((checkbox, i) => {
        if (i !== index)
          return {
            ...checkbox,
            checked: false,
          }
        if (i === index) {
          const item = {
            ...checkbox,
            checked: !checkbox.checked,
          }
          return item
        }
       return checkbox
     })
     setCheckboxValue(newValue)
     }    
    
    return (
       <View>
        {checkboxValue.map((checkbox, i) => (
            <View style={styles.checkboxContainer} key={i}>
              <CheckBox
                value={checkbox.checked}
                onValueChange={(value) => checkboxHandler(value, i)}
              />
              <Text style={styles.label}>{checkbox.label}</Text>
            </View>
          ))}
    
       </View>
     )
    }
    export default checkboxComponent
    

    【讨论】:

      【解决方案2】:

      您必须为每个控件设置一个特定的状态。有适合您的解决方案:

         export default class AgendaItemVote extends React.Component {
          constructor(props) {
              super(props);
              this.state = {
                  options: [
                      {
                          title: 'Ja',
                          checked: false
                      },
                      {
                          title: 'Nee',
                          checked: false
                      },
                      {
                          title: 'Onthouding',
                          checked: false
                      }
                  ]
              };
          }
      
          render() {
              return (
                  <View style={styles.container}>
                      <Card title="Titel Agendapunt">
                          <Text style={styles.paragraph}>
                              Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                              Vivamus at sapien at tellus interdum finibus. Nunc
                              sagittis tincidunt orci, non viverra ligula feugiat id.
                              Phasellus eleifend massa neque, eu scelerisque enim
                              feugiat ac.
                          </Text>
      
                          <View style={{ flexDirection: 'row' }}>
                              {this.state.options.map(opt => (
                                  <CheckBox
                                      title={opt.title}
                                      checked={opt.checked}
                                      key={opt.title}
                                      onClick={() => {
                                        opt.checked = !opt.checked;
                                        this.setState({
                                              options: [
                                                  ...this.state.options
                                              ]
                                          })
                                  ></CheckBox>)
                              )}
                          </View>
                          <View>
                              <Button title="Indienen" />
                          </View>
                      </Card>
                  </View>
              );
          }
      }
      
      const styles = StyleSheet.create({
          container: {
              flex: 1,
              alignItems: 'center',
              justifyContent: 'center',
              paddingTop: 40,
              backgroundColor: '#ecf0f1'
          },
          paragraph: {
              margin: 24,
              fontSize: 18,
              fontWeight: 'bold',
              textAlign: 'center',
              color: '#34495e'
          }
      });
      

      【讨论】:

      • 虽然这正是我所需要的,但在尝试使用此代码时,它没有显示任何复选框。
      • 已修复,立即尝试
      • 虽然复选框现在显示,但仍然无法检查它们。所以当我点击复选框时,什么也没有发生
      • 会很好:D
      • 我不得不将你的反应原生组件更改为一些 div repl.it/repls/StaticNeedyWebpages
      【解决方案3】:

      问题来了,

      checked={this.state.checked}
      

      当您将checked 设置为true 时,每个复选框都会被选中,因为您在每个复选框中都将此值用于this.state.checked

      从所有checkboxes 中删除checkedonPress,如果您想获得选中的checkbox 的值,则可以使用ref

      供您参考::Get the value of checkbox using ref in React

      【讨论】:

      • 虽然这对我有一点帮助,但在删除“选中”和“onPress”时,复选框不会在点击时选中
      • @Splekke 参考该问题的参考链接。
      猜你喜欢
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多