2017-06-03 114 views
0

我試圖在頁面上實現一個簡單的路由器。我有一個父類,它控制哪個視圖加載HutDBStatsRou​​ter和2個子類HutDBStatsHutDBPlayerView。 HutDBStats包含一個帶有TouchableOpacity的ListView,點擊時需要呈現HutDBPlayerView。我遇到了一個我相信的問題,因爲HutDBStats有它自己的道具,但我無法弄清楚如何正確地將它傳遞給父類HutDBStatsRou​​ter。從小孩訪問父項道具

爲了測試的目的,我在HutDBPlayerView中設置了相同的場景,並讓它呈現HutDBStats(它工作正常),但是當我有HutDBStats嘗試呈現HutDBPlayerView時,它不會工作。

該代碼相當大,所以我刪除了任何不必要的信息。我得到的錯誤是無法讀取未定義的的'changeComponent'屬性。

export default class HutDBStatsRouter extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      componentSelected: 'One', 
     } 
    } 
    changeComponent = (component) =>{ 
     this.setState({componentSelected: component}); 
    } 
    renderComponent(component) { 
     if(component == 'Two') { 
      return <HutDBStats changeComponent={this.changeComponent} /> 
     } else if(component == 'One') { 
      return <HutDBPlayerView changeComponent={this.changeComponent} /> 
     } 
    } 

    render() { 
     return (
      <View style={styles.container}> 
       {this.renderComponent(this.state.componentSelected)} 
      </View> 
     ); 
    } 
} 

class HutDBPlayerView extends Component { 
    render() { 
     return (
      <View> 
       <TouchableOpacity onPress={() => this.props.changeComponent('Two') }> 
        <Text>Go back to ListView</Text> 
       </TouchableOpacity> 
      </View> 
     ); 
    } 
} 

class HutDBStats extends Component { 

    constructor(props) { 
     super(props); 
     this.state = { 
      source  : [], 
      dataSource : new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), 
      loaded  : false, 
      page  : PAGE_LOAD_AMT, 
      search  : '', 
     }; 
    } 

    componentDidMount() { 
     this.fetchData(API_PATH + '&page=0',true, false); 
    } 

    ....... 
    ....... 

    renderList(d) { 
     return (
      <TouchableOpacity onPress={() => this.props.changeComponent('Two') }> 
       ... 
       </TouchableOpacity> 
     ); 
    } 
} 

任何幫助,非常感謝。我很新,反應原生。

回答

0

問題可能是HutDBPlayerView中的構造函數丟失。

class HutDBPlayerView extends Component { 
 
    constructor(props) { 
 
     super(props); 
 
    } 
 
    render() { 
 
     return (
 
      <View> 
 
       <TouchableOpacity onPress={() => this.props.changeComponent('Two') }> 
 
        <Text>Go back to ListView</Text> 
 
       </TouchableOpacity> 
 
      </View> 
 
     ); 
 
    } 
 
}

如果你想這是一個無狀態的組件,你甚至可以像這樣的代碼吧:

function HutDBPlayerView (props){ 
 
    return (
 
     <View> 
 
      <TouchableOpacity onPress={() => props.changeComponent('Two') }> 
 
       <Text>Go back to ListView</Text> 
 
      </TouchableOpacity> 
 
     </View> 
 
); 
 
}

+0

感謝。這不起作用,但我能夠通過使用:changeComponent = this.props.changeComponent(bind)來解決問題,然後重新發送ListView。 – sreid