I\'m new to React Native (and React), and I\'m trying to pass a function as a prop to a component.
My goal is to create a component where its onPress functionality c
Use arrow function for no care about binding this
.
And I recommend to check null before calling the props method.
App.js
export default class App extends Component {
constructor () {
super();
}
handlePress = () => {
// Do what you want.
}
render () {
return (
);
}
}
TouchableButton.js
import React, { Component } from 'react';
import { TouchableHighlight } from 'react-native';
import AppButton from "./app-button";
export default class TouchableButton extends Component {
constructor(props){
super(props);
}
handlePress = () => {
// Need to check to prevent null exception.
this.props.onPress?.(); // Same as this.props.onPress && this.props.onPress();
}
render () {
return (
);
}
}