将参数传递给prop函数,而无需使用箭头函数 [英] Pass parameters to prop function without using an arrow function

查看:64
本文介绍了将参数传递给prop函数,而无需使用箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说传递箭头函数作为道具并不理想,因为每次都会创建一个新函数,这将导致性能问题.但是,我不完全确定如何完全脱离它们,如下面的示例所示:

I've heard that passing an arrow function as a prop is not ideal because it creates a new function every time which will lead to performance issues. However, I'm not entirely sure how to completely move away from them, as can be seen by the example below:

class Home extends Component {

    onCardPress = (message) =>{
        alert(message)
    }

    render(){
        return(
            <View>
                <Card 
                    onCardPress={this.onCardPress}
                    message="Hello world!"
                />
            </View>
        )
    }
}

class Card extends Component {
    render(){
        const { onCardPress , message } = this.props;
        return(
            <TouchableOpacity
                activeOpacity={0.8}
                onPress={()=>{onCardPress(message)}}
            />
        )
    }
}

我尝试将 Card 中的 onPress 更改为 onPress = {onCardPress(message)} ,但是我知道这行不通因为我正在调用函数,而不是将函数对象传递给 TouchableOpacity onPress .什么是删除 TouchableOpacity 中的箭头功能,同时仍然能够从父组件 Home 传递 message 参数的正确"方法或最佳实践是什么?代码>?

I have tried changing onPress in Card to be onPress={onCardPress(message)}, but I know this doesn't work because I am invoking the function rather than passing a function object to the onPress of TouchableOpacity. What is the 'proper' way or best practice to remove the arrow function in TouchableOpacity while still being able to pass the message parameter from the parent component Home?

推荐答案

您不需要传递消息prop,因为您可以在组件中的任何位置访问它.只需在onPress属性中提供一个功能即可.在该功能中,只需访问组件的消息属性即可.

You don't need to pass the message prop because you can access it anywhere in the component. Just supply a function in the onPress prop. And in that function, just access the message prop of the component.

class Home extends Component {
  onCardPress = (message) => {
    alert(message)
  }
  render() {
    return (
      <View>
        <Card
          onCardPress={this.onCardPress}
          message="Hello world!"
        />
      </View>
    )
  }
}

class Card extends Component {
  onClick = () => {
    const { message, onCardPress } = this.props;
    onCardPress(message);
  };
  render() {
    return (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={this.onClick}
      />
    )
  }
}

这篇关于将参数传递给prop函数,而无需使用箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆