Home > OS >  Why isn't onPress calling the function?
Why isn't onPress calling the function?

Time:01-27

Entirely new to React Native. The problem isn't with the actual logic of the code. Tested it and it worked in a browser. Could it be with where code logic is placed inside render()? App doesn't render at all with it outside render(). Or is it because of where this.setState is?

[More Details. A lot more details. More Details. A lot more details. More Details. A lot more details. More Details. A lot more details. More Details. A lot more details. More Details. A lot more details. More Details. A lot more details. More Details. A lot more details. More Details. A lot more details.]

import React from 'react';
import type {Node} from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  Button,
} from 'react-native';

import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';




class App extends React.Component{


constructor(props) {
super(props);
this.state= {text: 'Lorem Ipsum admoniso'}
}



render() {


  // dataset for username 


const alpha= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];

const num= ['1','2','3','4','5','6','7','8','9','0'];


var counter = 0;
var Username;

// determine random length of the username

function UNlength() {
var UNlength = Math.random() *10;
UNlength = UNlength.toFixed(0);
if (UNlength == 0){UNlength = 1}
else {UNlength = UNlength};
return UNlength;}

var varUNlength = UNlength();
// function GenUsernameFn(){

// JS LOGICCCCCC

function UsernameFn(){


// 

  if (arguments.length == 0) {

// generate random nums as pickers

var PickerN = Math.random() * 10;
PickerN = PickerN.toFixed(0);


var PickerA = Math.random() * 26;
PickerA = PickerA.toFixed(0);

var PickerG = Math.random() * 10;
PickerG = PickerG.toFixed(0);



// Pickers for the first character in "Username"

var PickerUN = Math.random() * 10;
PickerUN = PickerUN.toFixed(0);

var PickerUA = Math.random() * 26;
PickerUA = PickerUA.toFixed(0);

var PickerUG = Math.random() * 10;
PickerUG = PickerUG.toFixed(0);


// choose randomly btw num and alpha. If Math.random 
// is an even num, option = alpha. If odd num, option = num

if (PickerG % 2 == 0) {var Chosen = num[PickerN];} else {var Chosen = alpha[PickerA];}

if (PickerUG % 2 == 0) { Username = num[PickerUN];} else { Username = alpha[PickerUA];}



//append each new choice to a string of previous choices
//when string = UNlength <= 10 chosen ranbdomly above, stop recursion.

// 'Username' declaration outside scope to allow loop access

Username = String(Username)   String(Chosen);
while (Username.length < varUNlength){UsernameFn(Username);}
}

else {
// algo for if Username is pre-defined 
// Pickers too

var PickerPN = Math.random() * 10;
PickerPN = PickerPN.toFixed(0);

var PickerPA = Math.random() * 26;
PickerPA = PickerPA.toFixed(0);

var PickerPG = Math.random() * 10;
PickerPG = PickerPG.toFixed(0);


if (PickerPG % 2 == 0) {var PickedNA =num[PickerPN];} else {var PickedNA = alpha[PickerPA];}

Username = String(Username)   String(PickedNA);
}

 while (Username.length < varUNlength){UsernameFn(Username);}
function Output(){
this.setState({text: {Username} });

}

} 


// actual react native

return (

    <View>

    <Text style={styles.TextCSS}>
{this.state.text}
    </Text>

<Button
  onPress={()=> UsernameFn() } 
  title="Click"
  color="#841584"
  accessibilityLabel="Learn more about this purple button"
/>  



    </View>
)
}  

}

CodePudding user response:

Your function Output is never called so you are never changing the state. Also in you should write this.setState({text: Username }) instead of this.setState({text: {Username} }).

To fix your issue you should write a if statement instead of a function like this:

if (Username.length >= varUNlength) {
    that.setState({ text: Username });
}

I wrote that instead of this because here this refers to the function UsernameFn instead of the App class component.

At the beginning of your render method you will need to add: const that = this; to make it work.

However your Class component still has multiple issues. Namely the functions should be class methods and not in the render method.

May I suggest a few optimizations:

  1. Refactor all the pickers to 2 helper functions in a helpers/getRandom.js file like so:
const getRandomLetter = () => {
    const characters = 'abcdefghijklmnopqrstuvwxyz';
    const letterNumber = Math.floor(Math.random() * 26);
    return characters[letterNumber];
};

const getRandomNumber = () => {
    return Math.floor(Math.random() * 10);
};

export { getRandomLetter, getRandomNumber };
  1. Create 2 Class methods : getRandomUsernameLength and getRandomUsername and keep your render method lean:
import React from 'react';
import { Text, View, Button, StyleSheet } from 'react-native';
import { getRandomLetter, getRandomNumber } from './helpers/getRandom';
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = { text: 'Lorem Ipsum admoniso' };
    }
    getRandomUsernameLength = () => {
        let UNlength = Math.random() * 10;
        UNlength = UNlength.toFixed(0);
        if (UNlength == 0) {
            UNlength = 1;
        } else {
            UNlength = UNlength;
        }
        return  UNlength;
    };

    getRandomUsername = () => {
        let username = '';
        const usernameLength = this.getRandomUsernameLength();
        while (username.length <= usernameLength) {
            const shouldBeLetter = Math.random() > 0.5;
            if (shouldBeLetter) {
                username  = getRandomLetter();
            } else {
                username  = getRandomNumber().toString();
            }
        }
        this.setState({ text: username });
    };

    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.TextCSS}>{this.state.text}</Text>

                <Button
                    onPress={this.getRandomUsername}
                    title="Click"
                    color="#841584"
                    accessibilityLabel="Learn more about this purple button"
                />
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
    TextCSS: {
        fontSize: 20,
    },
});
export default App;
  •  Tags:  
  • Related