在KeyPress上加载一个新的组件 - reactjs

时间:2017-04-03 05:52:45

标签: javascript reactjs

当我按下“Enter”按钮时,我正在尝试加载我创建的新组件。我已成功实现了onKeyPress功能,如下所示。

    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键时如何加载组件。

3 个答案:

答案 0 :(得分: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
};

答案 1 :(得分:0)

您如何处理索引中路由器定义中的路由?如果您没有父路线然后渲染它的孩子,而不是只有一堆命名路线,它可能无法工作。

答案 2 :(得分: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>

使用我的主App组件(路由器下的顶级路由)

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

这意味着&#39; /&#39;从App组件呈现,以及在&#39; /&#39;之后声明的任何路由。将被渲染到应用程序组件中,而不是它自己的页面。