【问题标题】:React routing on click event is not working [duplicate]点击事件的反应路由不起作用[重复]
【发布时间】:2019-10-13 13:48:14
【问题描述】:

我正在对按钮单击事件进行路由

  redirect(){

       return <Redirect to='/chat' />;

    }

它不工作。

我的主页-基础组件:

import React, { Fragment } from 'react';

  render() {

    const { value } = this.state;

    return (


        <Router>

          <div>
             <Switch>
            <Route exact={true} path="/" component={Home} />
            <Route path="/notify" component={Notify} />
            <Route path="/chat" component={Chat}/>
</Switch>

          </div>
          <footer className="foot">
            <BottomNavigation className="navbar navbar-default navbar-static-bottom navbar-fixed-bottom" value={value} onChange={this.handleChange} className={this.props.root}>

                <div className="navi">
                  <Link   to="/"> <BottomNavigationAction label="Home" value="Home" icon={<HomeIcon />} /></Link>
                </div>
                <div  className="navi">
                <Link to="/notify"><BottomNavigationAction label="Notification" value="Notification" icon={<NotifyIcon />} /></Link>
                </div>
                <div className="navi">
                <Link to="/chat"> <BottomNavigationAction label="Listen" value="Listen" icon={<LocationOnIcon />} /></Link>
                </div>

            </BottomNavigation>
          </footer>

我必须从我的子组件重定向到另一个组件, 这是我的子组件:

  <IconButton className={this.props.iconButton} aria-label="Search" onClick={this.redirect}>
        <SearchIcon />
      </IconButton>

redirect(){

       return <Redirect to='/chat' />;

    }

所以,但我也没有收到任何控制台错误。

【问题讨论】:

  • 它是因为Redirect 是一个 ui 元素,你必须渲染它,而 onClick 是一个事件处理程序,它不会渲染任何东西,它只会执行处理程序函数的主体。要解决您的问题,请使用this.props.history.push('/chat')

标签: reactjs typescript react-router


【解决方案1】:

&lt;Redirect /&gt; 是一个组件。所以,你应该这样使用它。

class App extends React.Component{
  state = { 
    isRedirect: false,
  }

  redirect = () => {
    this.setState({ isRedirect: true });
  }

  render() {
    return (
      <>
        <button onclick={this.redirect}> Redirect</button>

        {this.state.isRedirect ? <Redirect to="/" /> : null }
      </>
    ) 
  }

}

您可以使用历史 API

但你应该添加withRouter()

class App extends React.Component{
  render(){
    return(
      <>
        <button onClick={()=>{this.props.history.push('/')}}>Redirect</button>
      </>
    )
  }
}

export default withRouter(App);

【讨论】:

  • 我选择了它的历史 API 方法
  • @SridharPaiya 我同意,history API 更值得推荐
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2019-01-19
  • 2016-11-27
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
相关资源
最近更新 更多