繁体   English   中英

反应路由器链接与材料 ui 按钮提交

[英]react router link with material ui button submit

我在后端使用烧瓶并反应,将路由器和材料用户界面反应为前端。

我有:

  • 材料用户界面/核心 3.4.0,
  • 反应路由器dom 4.3.1

我正在尝试创建简单的注册表单。 我想提交表单的数据,然后使用反应路由器重定向到索引页面。 我的问题是 material-ui 按钮不适用于来自路由器的链接。 是否有可能以某种方式将这两者结合在一起?

我的代码:

进口:

import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { withStyles, Grid, Paper, Avatar, Typography, Button, TextField} from '@material-ui/core'
import LockIcon from '@material-ui/icons/LockOutlined'

并渲染返回:

render() {
  const { classes } = this.props
  const { user: { username, password } } = this.state
  return (
    <Grid container className={classes.root}>
      <Paper className={classes.paper}>

        <Avatar className={classes.avatar}>
          <LockIcon />
        </Avatar>

        <Typography component="h1" variant="h5">
          Sign up
        </Typography>

        <form onSubmit={this.saveUser}>
          <TextField label="Username" value={username} onChange={this.handleChange('username')} margin="normal" required fullWidth/>
          <TextField label="Password" value={password} onChange={this.handleChange('password')} margin="normal" required fullWidth type='password'/>

          <Button component={Link} to="/" type="submit" fullWidth variant="contained" color="primary">Sign Up</Button>

        </form>
      </Paper>
    </Grid>
  );
}

当我从 Button component={Link} to="/" 中删除时:

<Button type="submit" fullWidth variant="contained" color="primary">Sign Up</Button>

然后提交工作并将数据保存在数据库中。 当我删除type="submit" 时

<Button component={Link} to="/" fullWidth variant="contained" color="primary">Sign Up</Button>

然后重定向到索引页。

我可以以某种方式将这两者合二为一吗?

来自material-ui 的RaisedButton、FlatButton不再工作

添加到状态:

doRedirect: false

在渲染()中:

<Button type="submit" fullWidth variant="contained" color="primary">Sign Up</Button>

在提交处理程序中:

saveUser = () => {
    // **********
    // Your code to update database
    // **********

    this.setState({ doRedirect: true });
}

在渲染()中:

{ this.state.doRedirect && <Redirect to="/" /> }

而且当然:

import { Redirect } from 'react-router-dom'

在您的保存用户功能中,只需在保存用户后重定向即可。 你可以从 props 中获取历史

saveUser = event => {
  event.preventDefault()
  //update database with user
  this.props.history.location.push('new-route')
  // or you can use window.location
  window.location.href = 'new-route'
} 
 <Button
          onClick={() => {}}
          variant="outlined"
          component={Link}
          to={{
            pathname: `/`,
            search: location.search,
          }}
        >
          Submit
 </Button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM