[英]Function call in react native
我試圖在 class 中調用 function 但與以下語法混淆。
為什么調用 function 時需要使用 bind 方法?
為什么箭頭 function 沒有被執行?
import React, { Component } from 'react'
import { Text, View } from 'react-native'
//arrow function not getting executed!
myFun = data => {
console.warn(data);
}
myFun(data){
console.warn(data);
}
class Hello extends Component {
render() {
return (
<View>
{this.myFun("first")}
{this.myFun.bind(this, "second")}
</View>
);
}
}
export default Hello;
注意:我已經從第一種方法中刪除了評論!
應在 class 內部調用函數以使它們在此上下文中可用。
import React, { Component } from 'react'
import { Text, View } from 'react-native'
class Hello extends Component {
constructor(props) {
super(props);
}
//both normal fun and arrow fun should be inside class to get it executed!
myFun1 = data => {
console.warn(data);
}
myFun2(data){
console.warn(data);
}
render() {
return (
<View>
{this.myFun("first")}
{this.myFun2.bind(this, "second")}
</View>
);
}
}
export default Hello;
當您使用 this.myfun2.bind(this ) 時,您會將其添加到 **this ** 的當前上下文中。 基本上在那之后只有你能夠做到這一點。state、this.props、this.setstate 等
Also bind function returns a bounded function that, when executed later, the function will have the correct context ("this") for calling the original function. 因此,當 function 需要稍后在某些事件中調用時,可以使用 bind function 。
將 function 放入 class
在構造函數中綁定function:
this.handleChange = this.handleChange.bind(this);
綁定方法不執行函數/方法,僅返回帶有新上下文的 function (this)
在我們的例子中,關鍵字this
保留了封閉詞匯上下文的值Hello class
。 正如您在示例中看到的那樣, this
意味着Hello
沒有myFun
您正在嘗試調用該函數!
因此,要么將 function 放在 class 內,要么很快將調用方法更改為myFun("first")
。
最后,如果您需要在 function 中使用this
關鍵字,則必須使用bind(this)
方法。
您需要按如下方式調用 function。
import React, { Component } from 'react'
import { Text, View } from 'react-native'
myFun = data => {
console.warn(data);
}
class Hello extends Component {
render() {
return (
<View>
{()=>this.myFun("first")}
</View>
);
}
}
export default Hello;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.