2017-04-03 35 views
0

我想加載一個新的組件,當我按下'Enter'按鈕時,我已經成功實現了onKeyPress功能,如下所示。加載一個新的組件onKeyPress - reactjs

class SearchBar extends Component { 

     constructor(props) { 

      super(props); 

      this.handleKeyPress = this.handleKeyPress.bind(this); 

     } 

     handleKeyPress(e) { 

      if (e.key === 'Enter') { 

       console.log("load new page"); 

      } 
     } 

     render() { 

      return (

       <div className="search_bar_div"> 

        <div className="search_bar_internal_div"> 

         {/* Search bar for desktop and tablets */} 
         <span className="Rev_logo">Revegator</span> 

         <input type="search" placeholder="Search here" className="search_bar" 
           onKeyPress={this.handleKeyPress}/> 

        </div> 

       </div> 
} 

我得到控制檯日誌正確但我遇到的問題是如何加載組件時,我按Enter鍵。

回答

1

你可以做的是建立路由爲您組件,然後動態地改變與this.context.router

class SearchBar extends Component { 

     constructor(props) { 

      super(props); 

      this.handleKeyPress = this.handleKeyPress.bind(this); 

     } 


     handleKeyPress(e) { 

      if (e.key === 'Enter') { 

       console.log("load new page"); 
       this.context.router.push('/home'); 
      } 
     } 

     render() { 

      return (

       <div className="search_bar_div"> 

        <div className="search_bar_internal_div"> 

         {/* Search bar for desktop and tablets */} 
         <span className="Rev_logo">Revegator</span> 

         <input type="search" placeholder="Search here" className="search_bar" 
           onKeyPress={this.handleKeyPress}/> 

        </div> 

       </div> 
      ) 
     } 
} 


SearchBar.contextTypes = { 
    router: React.PropTypes.func.isRequired 
}; 
+0

我收到一個錯誤,因爲錯誤'PropTypes'沒有定義 – CraZyDroiD

+0

你的更新答案有所改進。當我輸入時,我可以看到URL更改。但該頁面不會加載。如果我手動刷新頁面,相關頁面將加載。我該如何解決? – CraZyDroiD

+0

你能解決這個問題 –

0

你是如何處理的指數在你的路由器定義路線的路線?如果你沒有一個父路由然後呈現它的子節點,而不是隻有一堆命名路由,它可能不起作用。

+0

<路由器歷史= {browserHistory}> <路由路徑= 「/」 成分= {}的LandingPage /> , 這樣 – CraZyDroiD

0

例如,我的索引是這樣

ReactDOM.render(
    <Provider store={store}> 
    <Router history={browserHistory}> 
     <Route path='/' component={App}> 
     <IndexRoute component={Welcome} /> 
     <Route path='/signin' component={SignIn} /> 
     <Route path='/signout' component={SignOut} /> 
     <Route path='/register' component={SignUp} /> 
     <Route path='/map' component={Map} /> 
     <Route path='/dashboard' component={RequireAuth(Dashboard)} /> 
     <Route path='/admin' component={RequireAdmin(Admin)} /> 
     <Router path='*' component={Welcome} /> 
     </Route> 
</Router> 

與我的主應用程序組件(路由器下頂層路徑)

render() { 
return (
    <div> 
    <Header /> 
    {this.props.children} 
    </div> 
) 
} 

這意味着 '/'是從App組件渲染的,任何在'/'後面聲明的路由都將被渲染到應用程序組件中,而不是它自己的頁面。