2017-08-28 96 views
0

我有兩個屏幕。第一個屏幕是HomeScreen,第二個屏幕是ProfileScreen。 我在HomeScreen上使用了FlatList,我想推導航到另一個屏幕。但是,當我使用的代碼,我看到錯誤消息:「不能讀取屬性‘導航’的未定義」更改屏幕FlatList onPress

代碼一樣,

class ProfileScreen extends Component { 

    static navigationOptions = { 
     title: 'Profile', 
    }; 

    render() { 
     const { navigate } = props.navigation; 

     return <Text>Hello, I am profile!</Text>; 
    } 
} 




class HomeScreen extends Component { 

    static navigationOptions = { 
     title: 'Home', 
    }; 


    constructor(props) { 
     super(props); 

     this.state = { 
      data: [], 

     }; 


    } 

    getScreen() { 
     this.props.navigation.navigate('Profile') 
    } 

    render() { 

     return (
      <View> 
       <FlatList 
        data={this.state.data} 
        renderItem={({ item }) => (
         <TouchableHighlight underlayColor= 'transparent' onPress= {this.getScreen}> 
          <View style= {{width: 300, height: 'auto'}} > 
          <Text> {item.title} </Text> 
           <View style= {{width: 300, height: 1, backgroundColor: 'red', marginBottom: 30, marginTop: 15}} /> 
          </View> 
         </TouchableHighlight> 
        )} 
       /> 
      </View> 
     ); 
    } 
} 



const AppNavigator = StackNavigator({ 
    Home: { screen: HomeScreen }, 
    Profile: { screen: ProfileScreen } 
}); 
+0

嘗試使用this.props.navigation並在最後添加此行導出默認AppNavigator –

+0

我不明白,你能解釋一下嗎? – tersintersi

+0

更改常量{導航} = this.props.navigation –

回答

0

你失去的this上下文在您的實現。與函數調用修復:

renderItem={({ item }) => (
    <TouchableHighlight underlayColor='transparent' onPress={() => this.getScreen()}> 
    ... 
    </TouchableHighlight> 
)} 

此外,您可以使用模式:

const { navigate } = this.props.navigation; 

navigate('Profile'); 
+0

這可能不是原因,我遇到同樣的問題,它不起作用 – hanzichi

0

裏面的構造函數綁定給你的getScreen方法。

只需在構造函數中添加以下行即可。

this.getScreen = this.getScreen.bind(this);