【问题标题】:Material UI button not redirecting to path材质 UI 按钮未重定向到路径
【发布时间】:2020-09-02 03:15:58
【问题描述】:

我有一个带有 onClick 功能的按钮,可以通过 props 重定向到某个组件

<Button
  variant="contained"
  color="primary"
  className={classes.button}
  endIcon={<SendIcon/>}
  onClick={() => {
        <Redirect 
         to={{
          pathname: '/view',
           state: {
            id: row.id
                  }
             }}
          />
         }}
 >
    View History
 </Button>

我的路线代码

<Route exact path="/view"  render={(props) => <NewTestComp {...props}/>} />

按钮没有重定向我尝试了很多不同的解决方案,但我找不到答案

【问题讨论】:

    标签: javascript reactjs redirect react-router material-ui


    【解决方案1】:

    您需要使用history.push 重定向到新页面,并且需要渲染Redirect 组件才能生效,并且onClick 处理程序不会渲染返回值

    <Button
      variant="contained"
      color="primary"
      className={classes.button}
      endIcon={<SendIcon/>}
      onClick={() => {
            props.history.push({
              pathname: '/view',
               state: {
                id: row.id
               }
            });
      }
     >
        View History
     </Button>
    

    Redirect would be to setStaterender the component conditionally的使用方式

    <Button
      variant="contained"
      color="primary"
      className={classes.button}
      endIcon={<SendIcon/>}
      onClick={() => {
            this.setState({ redirectWithState: {
                id: row.id
            }})
     >
        View History
     </Button>
    { redirectWithState && <Redirect 
             to={{
              pathname: '/view',
               state: redirectWithState
                 }}
              />
             }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 2020-02-06
      • 2021-07-23
      相关资源
      最近更新 更多