React Native에서 라디오 버튼을 구현하는 방법
React 코드를 React Native로 변환합니다.그래서 라디오 버튼을 구현해야 합니다.
베어본 RN만으로 라디오 버튼을 쉽게 흉내낼 수 있습니다.다음은 제가 사용하는 간단한 구현입니다.사이즈, 색상 등을 원하는 대로 조정.이렇게 되어 있습니다(다른 색조와 약간의 텍스트가 있음).더하다TouchableOpacity
버튼을 눌러서 무언가를 할 수 있게 합니다.
function RadioButton(props) {
return (
<View style={[{
height: 24,
width: 24,
borderRadius: 12,
borderWidth: 2,
borderColor: '#000',
alignItems: 'center',
justifyContent: 'center',
}, props.style]}>
{
props.selected ?
<View style={{
height: 12,
width: 12,
borderRadius: 6,
backgroundColor: '#000',
}}/>
: null
}
</View>
);
}
이것은 radioButtons(소스, php 단계별 채널 덕분에)를 만드는 또 다른 방법입니다.
방법 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 (
<View key={key}>
{this.state.checked == key ?
<TouchableOpacity style={styles.btn}>
<Image style={styles.img} source={require("./img/rb_selected.png")}/>
<Text>{data}</Text>
</TouchableOpacity>
:
<TouchableOpacity onPress={()=>{this.setState({checked: key})}} style={styles.btn}>
<Image style={styles.img} source={require("./img/rb_unselected.png")} />
<Text>{data}</Text>
</TouchableOpacity>
}
</View>
)
})}
const styles = StyleSheet.create({
img:{
height:20,
width: 20
},
btn:{
flexDirection: 'row'
}
});
아래 이미지를 img 폴더에 배치합니다.
방법 2
신규 개발자를 위한 LaneRettig ex 상세 설명
레인 리티그 덕분
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 (
<TouchableOpacity key={val.id} onPress={this.radioClick.bind(this, val.id)}>
<View style={{
height: 24,
width: 24,
borderRadius: 12,
borderWidth: 2,
borderColor: '#000',
alignItems: 'center',
justifyContent: 'center',
}}>
{
val.id == this.state.radioSelected ?
<View style={{
height: 12,
width: 12,
borderRadius: 6,
backgroundColor: '#000',
}} />
: null
}
</View>
</TouchableOpacity>
)
})
);
}
react-native-radio-buttons라고 하는 리액트 네이티브 컴포넌트가 있어 필요한 기능을 수행할 수 있습니다.
다음은 기능 컴포넌트를 사용한 라디오 버튼의 솔루션입니다.
주의 - 온/오프 라디오 아이콘에 이미지를 사용했습니다.
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;
사용하고 있다Checkbox
에react-native
옵션 버튼을 작성하기 위해 사용합니다.아래 코드를 참조하십시오.
constructor(props){
super(props);
this.state = {radioButton:'value1'};
}
render(){
return(
<View>
<CheckBox
title='value1'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={this.state.radioButton === 'value1'}
onPress={() => this.setState({radioButton: 'value1'})}
></CheckBox>
<CheckBox
title='value2'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={this.state.radioButton === 'value2'}
onPress={() => this.setState({radioButton: 'value2'})}
></CheckBox>
<CheckBox
title='value3'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={this.state.radioButton === 'value3'}
onPress={() => this.setState({radioButton: 'value3'})}
></CheckBox>
<CheckBox
title='value4'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={this.state.radioButton === 'value4'}
onPress={() => this.setState({radioButton: 'value4'})}
></CheckBox>
<CheckBox
title='value5'
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={this.state.radioButton === 'value5'}
onPress={() => this.setState({radioButton: 'value5'})}
></CheckBox>
</View>
);
}
라디오 버튼과 같은 동그라미 버튼으로 스타일을 설정할 수 있습니다.
const period = [
{
key: 1,
name : '1 Month',
value : 1,
},
{
key : 2,
name : '12 Month',
value : 12,
}
];
constructor(props) {
super(props);
this.state = {
value: 0,
};
}
onChangeTabs = (tabs) => {
this.setState({
value : tabs,
})
}
renderTabs = () => {
return period.map(item => (
<TouchableWithoutFeedback
key={item.key}
value={item.value}
onPress={this.onChangeTabs.bind(this, item.value)}
>
<View style={this.state.value == item.value ? styles.periodActive : styles.period}>
<Text style={styles.periodText}>{item.name}</Text>
</View>
</TouchableWithoutFeedback>
));
};
const styles = StyleSheet.create({
period: {
borderRadius: 5,
borderColor: '#fff',
borderWidth: 1,
marginHorizontal: 5,
},
periodActive: {
backgroundColor: '#333',
},
});
import React, { useState } from "react";
import { Ionicons } from "@expo/vector-icons";
import { View, Text, TouchableOpacity } from "react-native";
export default function RadioButton() {
const [radioButton, setRadioButton] = useState("Yes");
return (
<View style={{ flexDirection: "row", justifyContent: "space-around" }}>
<TouchableOpacity onPress={() => setRadioButton("Yes")}>
<Text>
<Ionicons name={ radioButton === "Yes" ? "radio-button-on" : "radio-button-off" } size={18} color="green" />
Yes
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setRadioButton("No")}>
<Text>
<Ionicons name={radioButton === "No" ? "radio-button-on" : "radio-button-off"} size={18} color="green" />
No
</Text>
</TouchableOpacity>
</View>
)}
react-native-radio-input을 사용할 수 있습니다.매우 사용하기 쉽습니다.
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>
.
.
import RadioForm, { RadioButton, RadioButtonInput, RadioButtonLabel } from 'react-native-simple-radio-button';
const radioProps = [
{ label: 'Male', value: false },
{ label: 'Female, value: true }
];
<View style={{ marginTop: 30 }}>
<RadioForm
buttonColor={gray}
buttonSize={12}
radioStyle={{paddingTop:25}}
selectedButtonColor="#000000"
radio_props={radioProps}
initial={0}
animation={false}
onPress={(value) => setGender(value)}
/>
</View>
커스텀 라디오 버튼을 사용하고 있습니다.group.it 스타일도 커스터마이즈 할 수 있습니다.
// radio button component
import React, { useState } from 'react'
import { Text, TouchableOpacity, View } from 'react-native'
const RadioButtons = (props) => {
const radioPress = () => {
props.setChecked(props?.item?.id)
}
return (
<View style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
margin:5,
}}>
<TouchableOpacity style={{
}} onPress={radioPress}>
<View style={[{
height: 24,
width: 24,
borderRadius: 12,
borderWidth: 2,
borderColor: '#000',
alignItems: 'center',
justifyContent: 'center',
}, props.style]}>
{
props?.checked == props?.item?.id ?
<View style={{
height: 12,
width: 12,
borderRadius: 6,
backgroundColor: '#000',
}} />
: null
}
</View>
</TouchableOpacity>
<Text style={{
marginLeft: 5,
fontWeight:"500",
fontSize:20,
textTransform:"capitalize"
}}>
{props?.item?.label}
</Text>
</View>
)
}
export default RadioButtons
다음과 같은 모든 장소에서 사용됩니다.
<View style={{
flexDirection:"row",
flexWrap:"wrap",
}}>
{
[{label:'male',id:0}, {label:'female',id:1},
{label:'other',id:2}].map((item,i)=>{
return(
<RadioButtons key={i} item={item} checked=
{checked} setChecked={setChecked} />
)
})
}
</View>
언급URL : https://stackoverflow.com/questions/31889921/how-to-implement-radio-button-in-react-native
'programing' 카테고리의 다른 글
ASP.NET MVC 검증 폼(Angular 포함)JS (0) | 2023.04.03 |
---|---|
useRef "값을 참조하지만 여기서 유형으로 사용되고 있습니다." (0) | 2023.04.03 |
지시 정의 객체의 "요구"는 무엇을 취합니까? (0) | 2023.04.03 |
$httpBackend 조롱 - "예기치 않은 요청, 더 이상 예상되지 않은 요청" 처리 방법 (0) | 2023.04.03 |
워드프레스의 클라우드 프런트 SSL 문제.리다이렉트가 너무 많다 (0) | 2023.04.03 |