Call Function Onpress React Native

Call function onPress React Native

In you're render you're setting up the handler incorrectly, give this a try;

 <View>
<Icon
name='heart'
color={this.state.myColor}
size= {45}
style={{marginLeft:40}}
onPress={this.handleClick}
/>
</View>

The syntax you're using would make sense for declaring an anonymous function inline or something but since your handler is defined on the class, you just reference it (not call it) using this.functionName in the props.

React Native Button onPress function example

You should do this if you don't need to pass an argument to your function :

<Button onPress={this.refreshData}>

Doing this <Button onPress={()=>this.refreshData()}> may break optimizations.

From React doc:

Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.

How to programmatically call the onPress() method of Pressable?

There is no method with the name onPress on Pressable Component that you can call by reference. onPress is a prop you pass to the Pressable that accepts a function.

You can define a function before return so it can be available by both.

Try this

 const callPressableFunc = () => {
console.log('I want to print this');
};

return (
<View>
<Pressable
style={{width: 100, height: 100, backgroundColor: 'yellow'}}
onPress={callPressableFunc}
ref={pressableRef}
/>
<Button title="Klick me" onPress={callPressableFunc} />
</View>
);

call function without onpress react native

You can simply get your key value with componentDidMount. As you should know, when the App runs and comes to the current screen, there is a flow of methods will be called before and after rendering the render function. So ComponentDidMount comes after render function is called. So since you need to only display the key value, just follow below code.

constructor(props) {
super(props);
this.state = {
myKey:''
}
}

getKey = async() => {
try {
const value = await AsyncStorage.getItem('@MySuperStore:key');
this.setState({ myKey: value });
} catch (error) {
console.log("Error retrieving data" + error);
}
}

componentDidMount(){
this.getKey();
}

render() {
return (
<View style={styles.container}>
<Button
style={styles.formButton}
onPress={this.getKey.bind(this)}
title="Get Key"
color="#2196f3"
accessibilityLabel="Get Key"
/>
<Text >
Stored key is {this.state.myKey}
</Text>
</View>
)
}

Whenever render function being called, in that time, still key value is not set. So, this.state.myKey would be just Stored key is. But after that, once the componentDidMount called, it sets the myKey value and change states. Which will trig render function to render everything again. That would show your key value within the text component eventually without touching any button.



Related Topics



Leave a reply



Submit