传递函数样式之间的差异

Ngu*_* Vũ 5 javascript react-native

这些函数调用样式之间有什么区别?

onPress = { () => { this.myFunctions() } }
Run Code Online (Sandbox Code Playgroud)

onPress = { this.myFunctions() }
Run Code Online (Sandbox Code Playgroud)

Joj*_*rte 6

onPress={() =>{this.myFunctions()}}

您正在传递一个匿名函数,该函数在调用onPress之后将调用 this.myFunctions()

onPress={this.myFunctions()}

您正在传递给onPress,其返回值this.myFunctions意味着每次组件调用render时都会执行此返回值。

上面两种将函数传递到React组件中的方法都不建议在性能上使用。使用上述方法会使每次onparent呈现时带有onPress的函数重新呈现,因为在对以前的匿名函数声明进行浅比较时,这将导致两个函数不相等,因为通过引用进行比较。

建议在下面使用:

onPress={this.myFunctions}

您在哪里传递函数的引用myFunctions。并且每当父项重新渲染时,一旦组件检查新的myFunctions是否与先前的渲染相同,它将返回true,并且不会再次渲染子项。