How to implement radio button in React Native

前端 未结 8 2289
不思量自难忘°
不思量自难忘° 2020-12-25 11:18

I am converting React code to React Native. So I need to implement radio buttons.

相关标签:
8条回答
  • 2020-12-25 12:22

    You can use react-native-radio-input. Its very simple to use.

    import RadioGroup,{Radio} from "react-native-radio-input";
    .
    .
    .
    //Receive the checked value (ES6 syntax)
    getChecked = (value) => {
    // value = our checked value
    alert(value)
    }
     <RadioGroup getChecked={this.getChecked}>
      <Radio iconName={"lens"} label={"The first option"} value={"A"} />
      <Radio iconName={"lens"} label={"The first option"} value={"B"} />
      <Radio iconName={"lens"} label={"I need numbers"} value={1} />
      <Radio label={"Is IconName Optional?"} value={"Yes"} />
      <Radio label={"Show Sentence Value"} value={"This is a Sentence"} />
    </RadioGroup>
    .
    .
    
    0 讨论(0)
  • 2020-12-25 12:25

    Here is my solution for radio button using functional components.

    Note - I have used images for checked & unchecked radio icon

    import React, {useState} from 'react';
    import {View, Text, StyleSheet, TouchableOpacity, Image} from 'react-native';
    
    const Radio = () => {
      const [checked, setChecked] = useState(0);
      var gender = ['Male', 'Female'];
      return (
        <View>
          <View style={styles.btn}>
            {gender.map((gender, key) => {
              return (
                <View key={gender}>
                  {checked == key ? (
                    <TouchableOpacity style={styles.btn}>
                      <Image
                        style={styles.img}
                        source={require('../images/radio_Checked.jpg')}
                      />
                      <Text>{gender}</Text>
                    </TouchableOpacity>
                  ) : (
                    <TouchableOpacity
                      onPress={() => {
                        setChecked(key);
                      }}
                      style={styles.btn}>
                      <Image
                        style={styles.img}
                        source={require('../images/radio_Unchecked.png')}
                      />
                      <Text>{gender}</Text>
                    </TouchableOpacity>
                  )}
                </View>
              );
            })}
          </View>
          {/* <Text>{gender[checked]}</Text> */}
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      radio: {
        flexDirection: 'row',
      },
      img: {
        height: 20,
        width: 20,
        marginHorizontal: 5,
      },
      btn: {
        flexDirection: 'row',
        alignItems: 'center',
      },
    });
    
    export default Radio;
    
    0 讨论(0)
提交回复
热议问题