将本机传递函数作为propsreact到子组件

IT技术 javascript reactjs react-native
2021-04-22 06:18:42

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

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

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

应用程序.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>
    );
  }
}

我将 handlePress 函数作为props handlePress 传递。我希望 TouchableButton 的props包含该功能,但它不存在。

3个回答

解决方案

使用箭头函数无需关心绑定this

我建议在调用 props 方法之前检查 null。

应用程序.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>
    );
  }
}

亲爱的杰夫,我正在尝试使用您的解决方案,但出现此错误:“未定义不是对象(正在评估 'navigation.getParam”),您知道我该怎么做吗?
2021-05-26 06:18:42
@Niloufar 你好。我认为这是与您的react-navigation. 如果您提出新问题,包括您的代码,请在此处留下链接。我会帮你。
2021-06-02 06:18:42
谢谢。这是我的问题:stackoverflow.com/questions/56412797/...
2021-06-12 06:18:42

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

几乎相同的第一个是应该执行以获取函数的表达式。第二个是函数对象本身。
2021-05-24 06:18:42
@Jerred 在创建 handlePress 方法时使用的是常规函数,因此当 handlePress 是常规函数时传递 this.handlePress.bind(this) 与当 handlePress 是箭头函数时传递 this.handlePress 相同。
2021-06-22 06:18:42
// Parent

handleClick( name ){
   alert(name);
}

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

// Children

let { func } = this.props;

func( 'VARIABLE' );