타닥타닥 개발자의 일상

react radio버튼 이용하여 값 선택하기 radiogroup radiobutton 본문

코딩 기록/react

react radio버튼 이용하여 값 선택하기 radiogroup radiobutton

NomadHaven 2022. 3. 7. 17:36

프로젝트 생성후 아래의 설치문을 입력해서 radiobutton을 import한다.

설치문
npm i react-native-flexi-radio-button --save

설치문을 입력한뒤 생성된

node_modules>react-navtive-flexi-readio-button>lib를 방문하여

radioButton.js와 radioGroup.js를 편집해준다.

radioButton.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  StyleSheet,
  View,
  Text,
  TouchableWithoutFeedback
} from 'react-native';

export default class RadioButton extends Component{
    constructor(props, context){
        super(props, context)
    }

    static componentDidUpdate(nextProps){
		this.setState({
			selectedIndex: nextProps.selectedIndex
		})
	}

    getRadioStyle(){
        return {
            height: this.context.size,
	        width: this.context.size,
	        borderRadius: this.context.size / 2,
	        borderWidth: this.context.thickness,
	        borderColor: this.props.isSelected && this.props.activeColor?this.props.activeColor:this.context.color,
        }
    }

    getRadioDotStyle(){
        return {
            height: this.context.size / 2,
            width: this.context.size / 2,
            borderRadius: this.context.size / 4,
            backgroundColor: this.props.color || this.props.activeColor,
        }
    }

    isSelected(){
        if(this.props.isSelected)
            return <View style={this.getRadioDotStyle()}/>
    }
    render(){
        var {children} = this.props
        return(
            <View style={{opacity: this.props.disabled?0.4:1}}>
                <TouchableWithoutFeedback
                    disabled={this.props.disabled}
                    onPress={() => this.context.onSelect(this.props.index, this.props.value)}
                >
                    <View style={[styles.container, this.props.style, this.props.isSelected?{backgroundColor: this.context.highlightColor}:null]}>
                        <View style={[styles.radio, this.getRadioStyle()]}>
                            {this.isSelected()}
                        </View>
                        <View style={styles.item}>
                            {children}
                        </View>
                    </View>
            </TouchableWithoutFeedback>
          </View>
        )
    }
}

RadioButton.contextTypes = {
        onSelect: PropTypes.func.isRequired,
        size: PropTypes.number.isRequired,
        thickness: PropTypes.number.isRequired,
        color: PropTypes.string.isRequired,
        highlightColor: PropTypes.string
    }

let styles = StyleSheet.create({
  container:{
	  flexGrow: 1,
	  flexDirection: 'row',
	  padding: 10,
  },
  radio:{
	  alignItems: 'center',
	  justifyContent: 'center',
  },
  item: {
    marginLeft: 5,
    alignItems: 'center',
	justifyContent: 'center',
  }
})
radioGroup.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  StyleSheet,
  View,
  Text,
} from 'react-native';

import RadioButton from './radioButton'

const defaultSize = 20
const defaultThickness = 1
const defaultColor = '#007AFF'

export default  class RadioGroup extends Component{
    constructor(props, context){
        super(props, context)

        this.state = {
            selectedIndex: this.props.selectedIndex,
        }
        this.prevSelected = this.props.selectedIndex
        this.onSelect = this.onSelect.bind(this)
    }

    static componentWillReceiveProps(nextProps){
       // if(nextProps.selectedIndex != this.prevSelected){
        if(nextProps.selectedIndex != this.prevSelected){
            this.prevSelected = nextProps.selectedIndex
            this.setState({
                selectedIndex: nextProps.selectedIndex
            })
        }
	}

    getChildContext() {
        return {
            onSelect: this.onSelect ,
            size: this.props.size,
            thickness: this.props.thickness,
            color: this.props.color,
            highlightColor: this.props.highlightColor
        };
    }

    onSelect(index, value){
        this.setState({
            selectedIndex: index
        })
        if(this.props.onSelect)
            this.props.onSelect(index, value)
    }

    render(){
        var radioButtons = React.Children.map(this.props.children, (radioButton, index) => {
            let isSelected = this.state.selectedIndex == index
            let color = isSelected && this.props.activeColor?this.props.activeColor:this.props.color
            return (
                <RadioButton
                    color={color}
                    activeColor={this.props.activeColor}
                    {...radioButton.props}
                    index={index}
                    isSelected={isSelected}
                >
                    {radioButton.props.children}
                </RadioButton>
            )
        })

        return(
            <View style={this.props.style}>
                {radioButtons}
            </View>
        )
    }
}

RadioGroup.childContextTypes = {
    onSelect: PropTypes.func.isRequired,
    size: PropTypes.number.isRequired,
    thickness: PropTypes.number.isRequired,
    color: PropTypes.string.isRequired,
    activeColor: PropTypes.string,
    highlightColor: PropTypes.string,
}

RadioGroup.defaultProps = {
    size: defaultSize,
    thickness: defaultThickness,
    color: defaultColor,
    highlightColor: null,
}

 

 


App.tsx
import React, { useState } from "react";
import { Text, View } from "react-native";

import { RadioGroup, RadioButton } from 'react-native-flexi-radio-button'


export default function App(){


  const [checked, setChecked] = useState('first')

return(
  <View>
    <RadioGroup
      size={24}
      thickness={2}
      color='#9575b2'
      highlightColor='#ccc8b9'
      selectedIndex={1}
      onSelect = {
        (index:any, value:any) => console.log(index, value)
      }>
        <RadioButton value ="first"
          status={checked === 'first' ? 'checked':'unchecked'}
          opPress={()=>setChecked('first')}>
            <Text>Apple</Text>
          </RadioButton>

          <RadioButton value ="second"
          status={checked === 'second' ? 'checked':'unchecked'}
          opPress={()=>setChecked('second')}>
            <Text>BlueBerry</Text>
          </RadioButton>


    </RadioGroup>
  </View>
)
}
실행화면

 

버튼 선택시 콘솔창

Comments