React-Native에서 라디오 버튼 그룹 만들기

11029 단어
안녕하세요 여러분,

오늘 우리는 타사 라이브러리를 사용하지 않고 react-native에서 라디오 버튼 예제를 만들 것입니다.

먼저 다음 명령을 사용하여 새로운 반응 네이티브 프로젝트를 만듭니다. 템플릿을 선택하라는 메시지가 표시되면 기본 템플릿을 선택하십시오.

create-react-native-app radio-button-demo


그런 다음 프로젝트 디렉터리로 이동하고 앱을 시작합니다.

npm run ios


새로 만든 앱은 다음과 유사하게 표시됩니다.



이제 라디오 버튼을 추가하는 앱 작업을 시작하겠습니다.

먼저 프로젝트 디렉터리의 루트에 RadioButton.jsRadioButtonContainer.js라는 두 개의 파일을 만듭니다. 프로젝트 구조는 다음과 같습니다.



라디오 버튼은 이렇게 생겼습니다.



이제 단일 라디오 버튼에 대한 반응 구성 요소를 만들어 보겠습니다.

export default function RadioButton() {

  return (
    <TouchableOpacity style={styles.mainContainer}>
      <View style={[styles.radioButtonIcon]}>
        <View style={[styles.radioButtonIconInnerIcon]} />
      </View>
      <View style={[styles.radioButtonTextContainer]}>
        <Text style={styles.radioButtonText}>Option A</Text>
      </View>
    </TouchableOpacity>
  );
}


또한 다음 스타일을 추가하여 보기 좋게 만듭니다.

const styles = StyleSheet.create({
  mainContainer: {
    height: 50,
    marginTop: 5,
    marginBottom: 5,
    marginLeft: 10,
    marginRight: 10,
    justifyContent: "center",
    paddingLeft: 10,
    paddingRight: 10,
    borderWidth: 0.5,
    borderColor: "red",
    flexDirection: "row",
    alignItems: "center",
  },
  radioButtonIcon: {
    backgroundColor: "white",
    borderWidth: 3,
    borderColor: "red",
    height: 30,
    width: 30,
    borderRadius: 30 / 2,
    marginRight: 10,
    alignItems: "center",
    justifyContent: "center",
  },
  radioButtonIconInnerIcon: {
    height: 25,
    width: 25,
    backgroundColor: "red",
    borderRadius: 25 / 2,
    borderWidth: 3,
    borderColor: "white",
  },
  radioButtonTextContainer: {
    flex: 5,
    height: 50,
    justifyContent: "center",
    paddingLeft: 10,
  },
  radioButtonText: {
    fontSize: 18,
  },
});


이제 라디오 버튼에 대한 더 나은 UI가 있습니다. 하지만 라디오 버튼이 여러 개 있어야 합니다.

이제 정확히 다음과 같은 동적 데이터가 포함된 여러 라디오 버튼을 만들어 보겠습니다.



이를 위해 RadioButtonContainer.js , App.js , RadioButton.js 파일의 코드를 변경해야 합니다. 이러한 변경 사항을 적용해 보겠습니다.
RadioButtonContainer.js 파일 안에 다음 코드를 붙여넣습니다. 나중에 자세한 설명을 들으러 가겠습니다.

import React, { useState, useEffect } from "react";
import { View, Text } from "react-native";
import RadioButton from "./RadioButton";

export default function RadioButtonContainer({ values, onPress }) {
  const [currentSelectedItem, setCurrentSelectedItem] = useState(0);

  const _onPress = (idx) => {
    onPress(idx);
    setCurrentSelectedItem(idx);
  };

  const _renderRadioButtons = () => {
    return (values || []).map((listItem, idx) => {
      let isChecked = currentSelectedItem === idx ? true : false;
      return (
        <RadioButton
          key={idx}
          onRadioButtonPress={() => _onPress(idx)}
          isChecked={isChecked}
          text={listItem.text}
        />
      );
    });
  };
  return <View>{_renderRadioButtons()}</View>;
}


이제 이{values, onPress }가 무엇을 의미하는지 궁금할 것입니다. 이는 상위 구성 요소에서 이RadiobuttonContainer 구성 요소로 전달되는 props입니다. values에는 라디오 버튼에 대한 데이터 목록이 포함되고 onPress에는 각 라디오 버튼을 클릭할 때 호출되는 함수가 있습니다.

const [currentSelectedItem, setCurrentSelectedItem] = useState(0);


위의 줄을 사용하여 데이터 목록의 첫 번째 값이 기본적으로 선택되어 있는지 확인합니다.

그런 다음 JS 배열map 함수를 사용하여 RadioButton의 여러 구성 요소를 렌더링합니다.

  const _renderRadioButtons = () => {
    return (values || []).map((listItem, idx) => {
      let isChecked = currentSelectedItem === idx ? true : false;
      return (
        <RadioButton
          key={idx}
          onRadioButtonPress={() => _onPress(idx)}
          isChecked={isChecked}
          text={listItem.text}
        />
      );
    });
  };


이제 RadioButton 구성 요소에 전달된 여러 소품이 있음을 알 수 있습니다. 한번 봅시다.
  • onRadioButtonPress는 해당 라디오 버튼을 누를 때 호출되며 데이터 목록에 인덱스를 제공합니다.
  • isChecked는 각 라디오 버튼의 선택 여부를 결정합니다.
  • text는 라디오 버튼의 본문에 표시되는 텍스트를 담당합니다.

  • const _onPress = (idx) => {
        onPress(idx);
        setCurrentSelectedItem(idx);
      };
    


    위의 함수는 선택된 라디오 버튼의 UI를 변경하는 역할을 합니다. onPress는 상위 구성 요소에서 전달된 함수입니다. setCurrentSelectedItem는 현재 선택된 라디오 버튼을 업데이트합니다.

    이제 소품을 RadioButtonContainer 에 전달해야 합니다. 어떻게 수행되는지 알아 봅시다.
    App.js 파일의 내용을 모두 제거하고 다음 코드를 붙여넣습니다.

    import { StatusBar } from "expo-status-bar";
    import React from "react";
    import { StyleSheet, Text, View, SafeAreaView } from "react-native";
    import RadioButtonContainer from "./RadioButtonContainer";
    
    export default function App() {
      const data = [
        {
          text: "Option A",
        },
        {
          text: "Option B",
        },
        {
          text: "Option C",
        },
        {
          text: "Option E",
        },
        {
          text: "Option F",
        },
        {
          text: "Option G",
        },
      ];
    
      const onRadioButtonPress = (itemIdx) => {
        console.log("Clicked", itemIdx);
      };
    
      return (
        <SafeAreaView>
          <View style={styles.textContainer}>
            <Text style={styles.text}>Radio Button Demo</Text>
          </View>
    
          <RadioButtonContainer values={data} onPress={onRadioButtonPress} />
          <StatusBar style="auto" />
        </SafeAreaView>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: "#fff",
        alignItems: "center",
        justifyContent: "center",
      },
      textContainer: {
        justifyContent: "center",
        alignItems: "center",
        marginBottom: 10,
      },
      text: {
        fontSize: 20,
        fontWeight: "bold",
      },
    });
    


  • data는 라디오 버튼에 대한 옵션을 전달하는 데 사용되는 객체 배열입니다. 그러나 여기에서는 각 개체에 text 속성을 포함하는 모든 배열을 사용할 수 있습니다.
  • onRadioButtonPress는 선택한 색인을 매개변수로 사용하여 라디오 버튼을 클릭할 때마다 호출됩니다.

  • 다음으로 최신 변경 사항에 맞추기 위해 RadioButton.js 파일을 일부 변경해야 합니다.
    우선 부모 구성 요소에서 모든 소품을 잡아야 합니다.

    export default function RadioButton()
    


    위 줄을 다음으로 변경하십시오.

    export default function RadioButton({ isChecked, text, onRadioButtonPress })
    


    상위 구성 요소에서 소품을 잡기 위해. 또한 returnRadioButton 코드를

      return (
        <TouchableOpacity style={styles.mainContainer}>
          <View style={[styles.radioButtonIcon]}>
            <View style={[styles.radioButtonIconInnerIcon]} />
          </View>
          <View style={[styles.radioButtonTextContainer]}>
            <Text style={styles.radioButtonText}>Option A</Text>
          </View>
        </TouchableOpacity>
      );
    
    


    이에

      const _renderCheckedView = () => {
        return isChecked ? (
          <View style={[styles.radioButtonIconInnerIcon]} />
        ) : null;
      };
    
      return (
        <TouchableOpacity style={styles.mainContainer} onPress={onRadioButtonPress}>
          <View style={[styles.radioButtonIcon]}>{_renderCheckedView()}</View>
          <View style={[styles.radioButtonTextContainer]}>
            <Text style={styles.radioButtonText}>{text}</Text>
          </View>
        </TouchableOpacity>
      );
    


    모든 변경을 수행한 후 귀하의 RadioButton.js 파일은 다음과 같습니다.

    import React, { useState } from "react";
    import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
    
    export default function RadioButton({ isChecked, text, onRadioButtonPress }) {
      const _renderCheckedView = () => {
        return isChecked ? (
          <View style={[styles.radioButtonIconInnerIcon]} />
        ) : null;
      };
    
      return (
        <TouchableOpacity style={styles.mainContainer} onPress={onRadioButtonPress}>
          <View style={[styles.radioButtonIcon]}>{_renderCheckedView()}</View>
          <View style={[styles.radioButtonTextContainer]}>
            <Text style={styles.radioButtonText}>{text}</Text>
          </View>
        </TouchableOpacity>
      );
    }
    
    const styles = StyleSheet.create({
      mainContainer: {
        height: 50,
        marginTop: 5,
        marginBottom: 5,
        marginLeft: 10,
        marginRight: 10,
        justifyContent: "center",
        paddingLeft: 10,
        paddingRight: 10,
        borderWidth: 0.5,
        borderColor: "red",
        flexDirection: "row",
        alignItems: "center",
      },
      radioButtonIcon: {
        backgroundColor: "white",
        borderWidth: 3,
        borderColor: "red",
        height: 30,
        width: 30,
        borderRadius: 30 / 2,
        marginRight: 10,
        alignItems: "center",
        justifyContent: "center",
      },
      radioButtonIconInnerIcon: {
        height: 25,
        width: 25,
        backgroundColor: "red",
        borderRadius: 25 / 2,
        borderWidth: 3,
        borderColor: "white",
      },
      radioButtonTextContainer: {
        flex: 5,
        height: 50,
        justifyContent: "center",
        paddingLeft: 10,
      },
      radioButtonText: {
        fontSize: 18,
      },
    });
    


    위의 모든 단계를 수행하면 보기 좋은 라디오 버튼 그룹이 생성됩니다.

    좋은 웹페이지 즐겨찾기