首页 > 解决方案 > 如何在本机反应中检查单选按钮?

问题描述

我正在使用 React Native Paper 中的单选按钮。

单选按钮本身工作正常。

但是,如果我移动到另一个页面并再次选中单选按钮,则无法维护该复选框。

如何检查单选按钮?

我是 React Native 的新手。

import React from 'react';
import { StyleSheet, View, TouchableOpacity, Text } from 'react-native';
import { RadioButton } from 'react-native-paper';
import { Actions } from 'react-native-router-flux';

const category = [
    {
        label: '한식'
    },
    {
        label: '분식'
    },
    {
        label: '카페, 디저트'
    }
]

export default class CategoryPage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            value: ''
        }
    }

    matchingPage() {
        Actions.pop();
    }


    render() {
        return (
            <View style={styles.container}>
                <View style={{ flex: 9, justifyContent: 'center' }}>
                    <RadioButton.Group onValueChange={value => this.setState({ value })} value={this.state.value}>
                        {category.map((data, index) =>
                            <RadioButton.Item
                                key={index}
                                style={styles.radioStyle}
                                label={data.label}
                                value={data.label}
                                color='black' />
                        )}
                    </RadioButton.Group>
                </View>

                <View style={{ flex: 1, alignItems: 'center' }}>
                    <TouchableOpacity
                        style={styles.buttonStyle}
                        onPress={this.matchingPage}>
                        <Text style={styles.buttonTextStyle}>선택 완료</Text>
                    </TouchableOpacity>
                </View>

            </View>

        );
    }
}

标签: react-nativereact-native-iosreact-native-paper

解决方案


import * as React from 'react';
import { View } from 'react-native';
import { RadioButton } from 'react-native-paper';

const MyComponent = () => {
  const [checked, setChecked] = React.useState('first');

  return (
    <View>
      <RadioButton
        value="first"
        status={ checked === 'first' ? 'checked' : 'unchecked' }
        onPress={() => setChecked('first')}
      />
      <RadioButton
        value="second"
        status={ checked === 'second' ? 'checked' : 'unchecked' }
        onPress={() => setChecked('second')}
      />
    </View>
  );
};

export default MyComponent;

推荐阅读