如何将变量传递给函数引用? [英] How to pass variables to a function reference?

查看:86
本文介绍了如何将变量传递给函数引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你有需要在渲染中运行并且必须传递变量的函数时,在本机做出反应时,大多数人建议应该使用

In react native when you have functions that need to run at render and must pass variables, most people suggest that one should use

onPress{() => this.functionName(variable)}

但是当处理大型列表和复杂组件时,您必须优化码。为 flatList 中的每个renderItem创建一个新函数会降低性能,有时会大大降低性能,具体取决于您创建的每个renderItem的函数数量。所以建议从创建渲染函数到使用函数引用。像这样:

However when working with large lists and complex components you have to optimize your code. Creating a new function for every renderItem in a flatList reduces performance, sometimes hugely so depending on how many functions per renderItem you are creating. So the suggestion is to move from creating a function at render to using a function reference. Like this:

functionName = () => {
   //code
}

onPress={this.functionName}

但是我无法弄清楚如何使用此方法将变量传递给函数。

However I haven't been able to figure out how to pass variables to the function with this method.

如果你这样做:

onPress={this.functionName(variable}

它将在组件加载时立即运行该函数。

It will just run the function instantly on component load.

任何想法?

推荐答案

作为 Esther Cuan 建议,currying是要走的路。如果你使用动态创建的函数,机会是因此,创建这些函数所花费的时间远远少于每次变量重新渲染组件所花费的时间。效率方面,优先级应该是最小化变量,以便在不断重新清理之前将重新渲染最小化函数。

As Esther Cuan suggests, currying is the way to go. Chances are, if you are using dynamically created functions dependent on variable changes. Then the time spent on creating these functions is much less than the time spent rerendering the components every time the variables change. Efficiency wise, the priority should be to minimize variable changes in order to minimize rerenders long before the constant redecleration of functions.

但是如果你确定某些函数是一致的,即使是通过重新渲染,并且不希望它们在这里被重新声明,那么你如何能够交流克服:

If however you are certain that some functions are consistent, even through rerenders, and do not want them to be redeclared here's how you can achieve that:

class Component extends React.Component {
  functionName = (e) => {
    const { variable } = this.props
    // run logic on the event and variable
  } 

  render() {
    // some code
    onPress={this.functionName}
  }
}

你会注意到这种方法 functionName 只被声明一次。

You'll notice with this approach functionName is only declared once.

这种方法的性能缺陷是现在你必须创建另一个组件(以及可能与该类一起提供的生命周期方法),以便将变量作为prop传递,以便绕过currying的需要。

The performance flaw with this approach is that now you have to create another component (and possibly the lifecycle methods that come with the class) in order to pass variable as a prop, in order to bypass the need for currying.

这篇关于如何将变量传递给函数引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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