将本机传递函数作为prop反映到子组件

Jer*_*erd 8 javascript reactjs react-native

我是React Native(和React)的新手,我正在尝试将一个函数作为prop传递给一个组件.

我的目标是创建一个组件,其组件的实例化器可以设置其onPress功能,以便它更具可重用性.

到目前为止,这是我的代码.

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我传递handlePress函数作为prop handlePress.我希望TouchableButton的道具包含该功能,但它不存在.

Jef*_*ang 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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Mot*_*ets 5

编写时handlePress={this.handlePress.bind(this)}传递一个语句执行(当执行时和如果执行时返回一个函数)。期望的是传递函数本身 with handlePress={this.handlePress}(并在构造函数中进行绑定)或handlePress={() => this.handlePress()}传递一个匿名函数,该函数在执行时将在this类上下文中执行handlePress。