如何在 React 本机的 RadioGroup 中获取所选项目



如何从无线电组获取选定的值。

state = {
        gender: '',
        data: [
            {
                label: 'male',
                value: "Male",
            },
            {
                label: 'female',
                value: "Female",
            }
        ],
    }
render() {
        return (
               <View style={styles.radioGroupContainer}>
                        <Text style={styles.textLableStyle}>Select Gender</Text>
                        <RadioGroup style={alignItems = 'flex-start'} 
                                    radioButtons={this.state.data} 
                        onPress={
                            this.onPress
                            } />
                    </View>
               )
         }

注意:在选择单选按钮时,我希望在性别变量中值。

通过在项目根目录中输入以下命令来安装包。

npm i react-native-radio-buttons-group --save

基本用法

import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import RadioGroup from 'react-native-radio-buttons-group';
export default class Vertical extends Component {
  state = {
    data: [
      {
        label: 'Default value is same as label',
      },
      {
        label: 'Value is different',
        value: "I'm not same as label",
      },
      {
        label: 'Color',
        color: 'green',
      },
      {
        disabled: true,
        label: 'Disabled',
      },
      {
        label: 'Size',
        size: 32,
      },
    ],
  };
  // update state
  onPress = data => this.setState({ data });
  render() {
    let selectedButton = this.state.data.find(e => e.selected == true);
    selectedButton = selectedButton ? selectedButton.value : this.state.data[0].label;
    return (
      <View style={styles.container}>
        <Text style={{ fontSize: 18, marginBottom: 50 }}>
          Value = {selectedButton}
        </Text>
        <RadioGroup radioButtons={this.state.data} onPress={this.onPress} />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

输出

使RadioGroup

像这样,只给RadioGroup标签。 通过放置该代码,您将获得性别状态的值。

<RadioGroup style={alignItems = 'flex-start'} 
    radioButtons={this.state.data} 
    onPress={data => this.setState({gender: data })} />

相关内容

  • 没有找到相关文章

最新更新