2017-07-21 74 views
0

我是新來reactnativereactnative通導航到子視圖

我使用FlatListapp.js,並使用StackNavigator對於這樣的場景之間導航:

class HomeScreen extends React.Component { 
    static navigationOptions = { 
    title: 'Content', 
    }; 


    render() { 
    const { navigate } = this.props.navigation; 
    return (
     <View style={styles.container}> 
     <FlatList 
     data = {myData} 
      renderItem={({item}) => 
          <Text style={styles.someStyle} 
            onPress={()=> 
              navigate("Detail", 
                {item: item});}> 
          {item.text}</Text> 
         } 
     />   
     </View> 
    ); 
    } 
} 

上面的代碼將很好地工作:當我按下一個列出的項目,將加載另一個場景以顯示項目內容的詳細信息。

但因爲我想爲所列項目複雜的造型,我認爲這將是方便的,我在這樣的一個子視圖定義的列表項目:

class MyHomeListItem extends React.PureComponent { 
    render(){ 
     return (
      <View style={styles.item}> 
       <Image 
       source={require('./assets/book.png')} 
       style={styles.listImageIcon} 
       /> 
       // as you can see the following `onPress` was intended for 
       // the same poperse which should load another secene to show the detail. 
       <Text onPress={()=> 
           {this.props.ref("Detail", 
               {item: this.props.item});}} 
        style={styles.listItemHomeText}> 

        {this.props.chapterName}: {this.props.chapterTitle} 
       </Text> 
      </View> 
     ); 
    } 
} 

而且我想通過在數據FlatList作爲一個屬性,如:

<FlatList 
    data = {myData} 

     renderItem={({item}) => <MyHomeListItem chapterName={item.chapterName} chapterTitle={item.chapterTitle} ref={navigate} /> } 
    /> 

如果我沒有在navigate功能傳遞給子視圖,那麼就會出問題,我認爲是好的,所以我將它傳遞通過ref到目前爲止是的參考navigate功能(我想)或只是通過ref={this}和在子視圖中使用this.props.ref.navigate(...),但要麼不工作。

它會顯示:

所以
_this3.props.ref is not a function....'_this3.props.ref' is undefined 

enter image description here

我怎樣才能做到這一點?

Furthur多,其實我是想整子視圖聽onPress但我沒有找到<View>

+0

子視圖中的屬性值是什麼? – error404

+0

'_this3.props.ref不是一個函數...._ this3.props.ref是不確定的' – armnotstrong

+0

我的意思是你可以在render方法中使用console.log(this.props)共享完整的日誌。在return語句之前放置該行並共享日誌。 – error404

回答

1

onPress屬性,我相信ref是用於分配的子組件是在裁判保留道具的父組件,以便父組件可以輕鬆引用子組件。 嘗試它向下傳遞直通navigation={navigate}

另外,如果你想onPress整個View,嘗試在Touchable的一個包裹View,即TouchableHighlightTouchableOpacity,或TouchableWithoutFeedback。並將onPress作爲道具傳遞給Touchable組件。

另外,親自,我更喜歡限定所述主頁的navigation邏輯,並在項目組件onPress函數將只是傳回相應的對象的行備份經由onRowPress丙從主屏幕組件向下傳遞。 這樣,導航邏輯並不是全部,行項組件可能足夠通用,以至於onPress函數總是會傳回相應的對象。

+0

嘿剛剛嘗試導航= {導航},它的工作,編輯答案接受它如果你不介意,謝謝提醒ref是一個保留字。 – armnotstrong