Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

javascript - 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 instantiator of the component, so that it is more reusable.

Here is my code so far.

App.js

import React, { Component } from 'react';
import { View } from 'react-native';
import TouchableButton from './components/touchable-button';

export default class App extends Component<Props> {
  constructor () {
    super();
  }

  handlePress () {
    // this should be called when my custom component is clicked
  }

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

TouchableButton.js

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

export default class TouchableButton extends Component {
  handlePress;

  constructor(props){
    super(props);
  }

  render () {
    return (
      <TouchableHighlight onPress={
        this.props.handlePress
      }>
        <AppButton/>
      </TouchableHighlight>
    );
  }
}

I am passing the handlePress function as the prop handlePress. I would expect the TouchableButton's props to contain that function, however it isn't there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...