How to implement radio button in React Native

前端 未结 8 2346
不思量自难忘°
不思量自难忘° 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:02

    This is another way of creating radioButtons (Source, thanks to php step by step channel)

    Method 1

    constructor(props) {
        super(props);
        this.state = {
            radioBtnsData: ['Item1', 'Item2', 'Item3'],
            checked: 0
        }
    }
    

    import { View, TextInput, TouchableOpacity } from 'react-native';
    
    {this.state.radioBtnsData.map((data, key) => {
        return (
            
                {this.state.checked == key ?
                    
                        
                        {data}
                    
                    :
                    {this.setState({checked: key})}} style={styles.btn}>
                        
                        {data}
                    
                }
            
        )
    })}
    

    const styles = StyleSheet.create({
        img:{
            height:20,
            width: 20
        },
        btn:{
            flexDirection: 'row'
        }
    });
    

    Place below images in img folder

    Method 2

    Elaborated LaneRettig ex for new developers

    Thanks to Lane Rettig

    constructor(props){
        super(props);
        this.state = {
          radioSelected: 1
        }
      }
    
    
      radioClick(id) {
        this.setState({
          radioSelected: id
        })
      }
    
      render() {
    
        const products = [{
          id: 1
        },
        {
          id: 2
        },
        {
          id: 3
        }];
    
        return (
          products.map((val) => {
            return (
              
                
                  {
                    val.id == this.state.radioSelected ?
                      
                      : null
                  }
                
              
            )
          })
        );
      }
    

提交回复
热议问题