2015-09-01 30 views
2

嗨,這是我第一次在javascript和react-native開發應用程序,這是一種noob問題。如何在__onRegionChangeComplete函數中調用_getData函數?我試圖this._getData()它顯示如何在函數中調用react-native函數?

error: undefined is not a function(evaluation'this._getData()')').

var React = require('react-native'); 

var { 
    StyleSheet, 
    Text, 
    View, 
    Image, 
    MapView, 
    Component, 
} = React; 

class Map extends Component { 
    render() { 
    return (
     <View style={styles.container}> 
     <MapView style={styles.map} 
      showsUserLocation={true} 
      onRegionChangeComplete={this._onRegionChangeComplete} 
     /> 
     </View> 
    ); 
    } 

    _onRegionChangeComplete(region) 
    { 

    } 

    _getData() 
    { 

    } 
} 

var styles = StyleSheet.create({ 
    container:{ 
    flex: 1 
    }, 
    map: { 
    flex: 1, 
    }, 
    image: { 
    width: 64, 
    height: 64 
    } 
}); 

module.exports = Map; 

回答

2

解決它通過改變擴展組件到createclass並在每個函數後面添加逗號。閱讀關於它們的簡要介紹是,createclass具有自動綁定功能,並且擴展組件不會爲您執行此操作,因此您必須自己綁定它們。

var React = require('react-native'); 

var { 
    StyleSheet, 
    Text, 
    View, 
    Image, 
    MapView, 
    Component, 
} = React; 

var Map = React.createClass({ 
    render(){ 
    return (
     <View style={styles.container}> 
     <MapView style={styles.map} 
      showsUserLocation={true} 
      rotateEnabled={false} 
      onRegionChangeComplete={this.onRegionChangeComplete} 
     /> 
     </View> 
    ); 
    }, 

    onRegionChangeComplete(region) { 
    this.getData(region) 
    }, 

    getData(region) { 

    }, 
}); 

var styles = StyleSheet.create({ 
    container:{ 
    flex: 1 
    }, 
    map: { 
    flex: 1, 
    }, 
    image: { 
    width: 64, 
    height: 64 
    } 
}); 

module.exports = Map; 
+0

這是自成立以來ES6錯誤。 – cube

+1

任何人都可以使用「新」方式(ES6,請參閱上面的註釋)更新此內容嗎?我有同樣的問題,但不想回退到「錯誤的」 – SVetter

+0

我認爲使用'extends'更好,並且與標準兼容,請參閱https://toddmotto.com/react-create-class-versus-組件/ –

0

一個語法注意,您應該解決可能會導致錯誤:在類的每一個方法的關閉括號後面添加一個逗號。嘗試並編輯您的帖子,看看是否有任何錯誤。 (對不起,我把這個評論,但沒有足夠的聲譽!)

2

讓我告訴你一個例子,並希望它可以幫助你。

1.當然,您可以使用ES5功能(createClass)而不是ES6(擴展類)方法來解決此綁定問題。

2.您可以繼續使用ES6,只需要謹慎地綁定它。 例如,在我的組件

_func1(){ 
    ... 
} 

_func2(){ 
    this._func1() 
} 
如果我想打電話給_func1()在FUNC2

,「這個」被綁定到_func2本身,當然,也沒有FUNC1()那裏。

但是,如果我在調用_func2()時將_func2()綁定到組件上下文,則問題將得到解決。

<subComponent subProp = {this._func2.bind(this)} /> 

希望它可以幫助你。

0

這個例子肯定有幫助

export default class Setup extends Component { 
    _onPressButton() { 
    Alert.alert('You tapped the button!') 
    } 

    render() { 
    return (
     <View style={styles.container}> 
     <View> 
     <Text h1>Login</Text> 
     </View> 
     <View> 
     <Button 
      onPress={this._onPressButton} 
      title="Learn More" 
      color="#841584" 
      accessibilityLabel="Learn more about this purple button" 
     /> 
     </View> 
     </View> 
    ); 
    } 
} 
相關問題