简体   繁体   中英

How to identify chosen radio button value React Native?

I would like the console to print a unique text for the different radio buttons. For example if the user chooses the radio button valued label1, the console should print 'You chose label1'. The file contains three radio buttons and their values that are from a different file. I save the users choice in a asyncstorage, when the button is pressed. This is my file:

import RadioButtonRN from 'radio-buttons-react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {Questions} from '../questions/questions_user'

export const ScreenOne = ({ }) => {
  const navigation = useNavigation();

  const question3 = Questions[2].question;
  const label1 = Questions[2].answers[0].answer;
  const label2 = Questions[2].answers[1].answer;
  const label3 = Questions[2].answers[2].answer;

  const [radioBtn, setSelectedRadioBtn] = useState('')

  const saveValue = () => {
    if (radioBtn) {
      AsyncStorage.setItem('radioValue', JSON.stringify(radioBtn))
      setSelectedRadioBtn('');
    } 
  }

  const data = [
    {
      label: label1
    },
    {
      label: label2
    },
    {
      label: label3
    }
  ];

  return (
    <ScreenContainer>
        <RadioButtonRN
          data={data}
          selectedBtn={(e) => setSelectedRadioBtn(e)}
          box={false}
          circleSize={14}
          activeColor={'#6175CF'}
          style={styles.radio}
        />
      </InputArea>
          <Button onPress={saveValue} />
    </ScreenContainer>
  )
}

export default ScreenOne


import AsyncStorage from '@react-native-async-storage/async-storage';
import {Questions} from '../questions/questions_user'

export const ScreenOne = ({ }) => {
  const navigation = useNavigation();

  const question3 = Questions[2].question;
  const label1 = Questions[2].answers[0].answer;
  const label2 = Questions[2].answers[1].answer;
  const label3 = Questions[2].answers[2].answer;

  const [radioBtn, setSelectedRadioBtn] = useState('')

  const saveValue = () => {
    if (radioBtn) {
      AsyncStorage.setItem('radioValue', JSON.stringify(radioBtn))
      setSelectedRadioBtn('');
    } 
  }

  const data = [
    {
      label: label1
    },
    {
      label: label2
    },
    {
      label: label3
    }
  ];

  return (
    <ScreenContainer>
        <RadioButtonRN
          data={data}
          selectedBtn={(e) => setSelectedRadioBtn(e)}
          box={false}
          circleSize={14}
          activeColor={'#6175CF'}
          style={styles.radio}
        />
      </InputArea>
          <Button onPress={saveValue} />

       <Text>{radioBtn.label}</Text>

    </ScreenContainer>
  )
}

export default ScreenOne;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM