2016-12-31 105 views
0

我正在處理React Native項目,我不知道爲什麼我不能引用Navigator對象。我收到一個錯誤:undefined is not an object (evaluating _this2.refs._navigator.push)。一秒後,當我的setTimeout函數觸發時,會發生錯誤。無法從React Native中引用Navigator

感謝任何幫助

這是我的代碼。

App.js

// ... some code initialization... 

class App extends Component { 
    constructor(props) { 
    super(props); 
    } 

    componentDidMount() { 
    setTimeout(() => { 
     this.refs._navigator.push(routes[1]); 
    }, 1000); 
    } 

    render() { 
    return(
     <Navigator 
     initialRoute={routes[0]} 
     initialRouteStack={routes} 
     renderScene={(route, navigator) => { 
      switch (route.index) { 
      case 0: 
       return <Home />; 
      case 1: 
       return <About />; 
      default: 
       return <Home />; 
      } 
     }} 
     ref={(nav) => { this._navigator = nav; }} 
     /> 
    ); 
    } 

} 

const routes = [ 
    {title: 'Home', index: 0}, 
    {title: 'About', index: 1}, 
    {title: 'Cars', index: 2} 
]; 

回答

0

嘗試在componentDidMount這樣做:

componentDidMount() { 
    setTimeout(() => { 
    this._navigator.push(routes[1]); 
    }, 1000); 
} 

這是因爲你引用的資產淨值爲this._navigator在你的導航參考。

+0

嘿@Nader,非常感謝。這對我來說似乎有些困惑,因爲在純粹的React中,我必須加上「refs」這個詞來獲得這個。順便一提。謝謝。 –

+1

@PabloDarde不是真的,你是在ref回調中分配'this._navigator',所以它在那裏可用 – Icepickle

+1

哦,你說得對,也許'refs'關鍵字是不推薦使用的引用方式的元素,如: **棄用** <元素ref ='myElement'... **推薦** <元素ref = {(el)=> {this.element = el; }} ... 謝謝 –

相關問題