Как установить только один флажок в приложении React Native для Android?

Я пытаюсь настроить свое первое приложение для Android в React Native.

Теперь есть эта карта (response-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',
    },
});

2 ответа

У меня была аналогичная проблема, после ее решения я пишу здесь свой ответ.

Рассмотрим пример ниже - (с крючками)

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

Вы должны иметь определенное состояние для каждого элемента управления. есть решение для вас:

   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
                                        ]
                                    })
                                }
                    </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'
    }
});

Проблема здесь,

checked={this.state.checked}

Когда вы установите checked в true каждый флажок проверяется, так как вы используете это значение для this.state.checked в каждом флажке.

Удалить checked а также onPress от всех checkboxes и если вы хотите получить значение проверено checkbox тогда вы можете использовать ref,

Для справки:: Получить значение флажка, используя ref в React

Другие вопросы по тегам