2017-09-02 206 views
0

這可能是一個簡單的問題,但我是React-Native的新手,現在我完全陷入困境。如何從React-Native的另一個函數調用函數?

如何從函數1調用函數2?

這是我嘗試過,但按下第一個按鈕時,它呈現一個錯誤,指出:

未定義不是(評估「this.function2()」)

功能
import React, { Component } from 'react'; 
import { 
AppRegistry, 
View, 
Image, 
TouchableOpacity, 
} from 'react-native'; 

export default class Example extends Component { 

    function1(){ 
     console.log('function1() called'); 
     ... 
     this.function2(); 
    }; 

    function2() { 
     console.log('function2() called'); 
     ... 
    }; 

    render() { 
     return (
      <View> 
       <TouchableOpacity onPress={this.function1}> 
        <Image source={require('../../../assets/img/button.png')} /> 
       </TouchableOpacity> 

       <TouchableOpacity onPress={this.function2}> 
        <Image source={require('../../../assets/img/button.png')} /> 
       </TouchableOpacity> 
      </View> 
     ); 
    }; 
} 

AppRegistry.registerComponent('Example',() => Example); 
+0

直接調用function2()怎麼樣? – user10089632

+0

@ user10089632因爲您有時可能想要在function1()中執行代碼,但有時也只能在function2()中執行代碼。它減少了冗餘。請參閱帖子中的編輯代碼。 – Misklahr

回答

2

嘗試此,

<TouchableOpacity onPress={() => this.function1()}> 
     <Image source={require('../../../assets/img/button.png')} /> 
</TouchableOpacity> 

脂肪箭頭功能具有更短的語法和詞彙綁定此值。箭頭功能始終是匿名的,並有效地將function (arguments) { expression }轉換爲arguments => expression。如果在箭頭之後使用表達式,則返回是隱式的,所以不需要返回。

+0

我明白了!我認爲這與範圍和約束有關。感謝您的幫助。 – Misklahr

4

如果該函數是一個回調函數並傳遞給另一個組件,則應該將它們綁定到組件構造器中。相比函數表達式

constructor(props) { 
    super(props); 

    this.function1 = this.function1.bind(this); 
    this.function2 = this.function2.bind(this); 
} 
相關問題