Skip to content Skip to sidebar Skip to footer

React Native Pass Function To Child Component As Prop

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 can be set by the

Solution 1:

Solution

Use arrow function for no care about binding this.

And I recommend to check null before calling the props method.

App.js

exportdefaultclassAppextendsComponent<Props> {
  constructor () {
    super();
  }

  handlePress = () => {
    // Do what you want. 
  }

  render () {
    return (
      <View><TouchableButtononPress={this.handlePress}/></View>
    );
  }
}

TouchableButton.js

importReact, { Component } from'react';
import { TouchableHighlight } from'react-native';
importAppButtonfrom"./app-button";

exportdefaultclassTouchableButtonextendsComponent {
  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 (
      <TouchableHighlightonPress={this.handlePress}><AppButton/></TouchableHighlight>
    );
  }
}

Solution 2:

When writing handlePress={this.handlePress.bind(this)} you passing a statement execution ( which when and if executed returns a function). What is expected is to pass the function itself either with handlePress={this.handlePress} (and do the binding in the constructor) or handlePress={() => this.handlePress()} which passes an anonymous function which when executed will execute handlePress in this class context.

Solution 3:

// ParenthandleClick( name ){
   alert(name);
}

<Child func={this.handleClick.bind(this)} />

// Childrenlet { func } = this.props;

func( 'VARIABLE' );

Post a Comment for "React Native Pass Function To Child Component As Prop"