![](/img/trans.png)
[英]React native. undefined is not object (evaluating 'this.props.navigator.push')
[英]React Native, NavigatorIOS, undefined is not an object (evaluating 'this.props.navigator.push')
我正在嘗試使用NavigatorIOS
所以在我的index.ios.js
我得到了:
'use strict';
var React = require('react-native');
var Home = require('./App/Components/Home');
var {
AppRegistry,
StyleSheet,
NavigatorIOS
} = React;
var styles = StyleSheet.create({
container:{
flex: 1,
backgroundColor: '#111111'
}
});
class ExampleApp extends React.Component{
render() {
return (
<NavigatorIOS
style={styles.container}
initialRoute={{
title: 'example',
component: Home
}} />
);
}
};
AppRegistry.registerComponent('exampleapp', () => ExampleApp);
module.exports = ExampleApp;
然后在Home.js
:
'use strict';
var React = require('react-native');
var Park = require('./Park');
var {
View,
StyleSheet,
Text,
TouchableHighlight
} = React;
var styles = StyleSheet.create({
...
});
class Home extends React.Component{
onPress() {
this.props.navigator.push({
title: 'Routed!',
component: Park
});
}
render() {
return (
<View style={styles.mainContainer}>
<Text> Testing React Native </Text>
<TouchableHighlight onPress={this.onPress} style={styles.button}>
<Text>Welcome to the NavigatorIOS . Press here!</Text>
</TouchableHighlight>
</View>
);
}
};
module.exports = Home;
我遇到的問題是,當我點擊TouchableHighlight
觸發onPress()
,我收到一個錯誤:
"Error: undefined is not an object (evaluating 'this.props.navigator')
所以它似乎無法從道具中找到navigator
但導航器應該通過NavigatorIOS
傳遞?
此外, Home
組件似乎有this.props.navigator
根據圖像:
任何提示?
我找到了幾個鏈接(人們有完全相同的問題,但沒有幫助):
由於您使用的是ES6,因此需要綁定“this”。
例如: onPress={this.onPress.bind(this)}
編輯:然而,這我一直在使用最近的另一種方式是對函數本身使用箭頭功能,因為它們會自動綁定外部this
。
onPress = () => {
this.props.navigator.push({
title: 'Routed!',
component: Park
});
};
您可以在constructor
函數中將函數綁定到this。
constructor(props) {
super(props);
this.onPress = this.onPress.bind(this);
}
然后在渲染時使用它而不綁定。
render() {
return (
<TouchableHighlight onPress={this.onPress} style={styles.button}>
<Text>Welcome to the NavigatorIOS. Press here!</Text>
</TouchableHighlight>
);
}
這樣做的好處是可以多次使用,也可以清理渲染方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.