React Native pass function to child component as prop

前端 未结 3 1580
面向向阳花
面向向阳花 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

    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.

    0 讨论(0)
  • 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<Props> {
      constructor () {
        super();
      }
    
      handlePress = () => {
        // Do what you want. 
      }
    
      render () {
        return (
          <View>
            <TouchableButton onPress={this.handlePress}/>
          </View>
        );
      }
    }

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

    0 讨论(0)
  • 2021-01-11 23:17
    // Parent
    
    handleClick( name ){
       alert(name);
    }
    
    <Child func={this.handleClick.bind(this)} />
    
    // Children
    
    let { func } = this.props;
    
    func( 'VARIABLE' );
    
    0 讨论(0)
提交回复
热议问题