React Native pass function to child component as prop

前端 未结 3 1588
面向向阳花
面向向阳花 2021-01-11 22:57

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

3条回答
  •  暖寄归人
    2021-01-11 23:10

    Solution

    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 (
          
            
          
        );
      }
    }

提交回复
热议问题