【问题标题】:How to Default export react withRouter while using material UI makeStyles如何在使用材质 UI makeStyles 时默认导出与Router 做出反应
【发布时间】:2021-05-15 16:02:51
【问题描述】:

我将 Material UI makeStyles 与类组件一起使用,并将使用样式添加为道具,同时默认将其导出为箭头函数。

export default () => {
  const classes = useStyles();

  return (
    <LoginClass classes={classes} />
  )
}

在 react 文档中,它指出你需要在使用 makestyles 时使用钩子,目前我一直在正确地做。

我现在面临的问题是我想用 react withRouter 来使用:

this.props.history.push

我在课堂上无法访问。

以下是我的代码,运行良好,但我无法将用户引导至其他页面。

const useStyles = makeStyles((theme) => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: '#009688',
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(1),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
    backgroundColor: '#33ab9f',
    '&:hover': {
      backgroundColor: '#009688',
    },
  },
}));
class LoginClass extends React.Component {
  
  handleSubmit(event) {
        this.props.history.push('/home') //dont have access to history unless I use withRouter
                      }
render() {
    const classes = this.props.classes;
    const { input } = this.state
    return (
      <React.Fragment>
        <CssBaseline />
        <MenuBarClass classes={classes} isLogin={this.state.isLogin} />
      </React.Fragment>
   )
  }
}

经过大量研究,我找到了一种将用户引导至其他页面的方法:

export default withRouter(withStyles(useStyles)(LoginClass))

但使用上述导出会扭曲我的整个页面设计。

任何使用类和 makeStyles 的解决方案将不胜感激。 谢谢你。 这样我就可以将用户引导到其他页面。

【问题讨论】:

    标签: javascript reactjs react-router material-ui


    【解决方案1】:

    试试这个方法:

    const styles = theme => ({
      paper: {
        marginTop: theme.spacing(8),
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
      },
      avatar: {
        margin: theme.spacing(1),
        backgroundColor: '#009688',
      },
      form: {
        width: '100%', // Fix IE 11 issue.
        marginTop: theme.spacing(1),
      },
      submit: {
        margin: theme.spacing(3, 0, 2),
        backgroundColor: '#33ab9f',
        '&:hover': {
          backgroundColor: '#009688',
        },
      },
    });      
    
    ...
    
    export default withRouter(withStyles(styles)(LoginClass)) 
    

    【讨论】:

    • 谢谢@MaxAlex。它解决了问题
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 2021-12-17
    • 2021-03-23
    • 2019-01-27
    • 1970-01-01
    相关资源
    最近更新 更多