我正在尝试为登录的用户验证我的电子邮件和密码TextField。我可以通过handleSubmit
函数捕获错误,但不确定如何将这些错误实现到MaterialUIerror
和helperText
字段中。
注意,我同时使用material-ui
和react-bootstrap
,这就是它们混合使用的原因。
Login.js-其中电子邮件和密码TextField是
import React, { Component } from 'react';
import firebase from '../firebase';
import { FiLogIn } from 'react-icons/fi';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField'
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
export class Login extends Component {
state = {
email : "",
password : ""
};
handleChange = (e) => {
const { id, value } = e.target
this.setState(prevState => ({
...prevState,
[id] : value
}))
};
handleSubmit = (e) => {
e.preventDefault();
const { email, password } = this.state;
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((user) => {
// User is signed in
})
.catch((error) => {
// Error
});
};
render() {
const { email, password } = this.state;
return (
<>
<Form className="sign-in-form">
<Form.Row className="align-items-center">
<Col xs="auto">
<Form.Group controlId="email">
<Form.Label srOnly>Email Address</Form.Label>
<TextField
id="email"
label="Email"
type="email"
variant="outlined"
aria-describedby="emailHelp"
placeholder="Enter email"
value={email}
onChange={this.handleChange}
/>
</Form.Group>
</Col>
<Col xs="auto">
<Form.Group controlId="password">
<Form.Label srOnly>Password</Form.Label>
<TextField
id="password"
label="Password"
variant="outlined"
type="password"
placeholder="Enter password"
value={password}
onChange={this.handleChange}
/>
</Form.Group>
</Col>
</Form.Row>
</Form>
<Button variant="contained" color="primary" className="login" type="submit" onClick={this.handleSubmit}><FiLogIn className="loginIcon" /> Login</Button>
</>
)
}
}
handleSubmit函数-其中捕获了的firebase验证错误
handleSubmit = (e) => {
e.preventDefault();
const { email, password } = this.state;
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((user) => {
// User is signed in
})
.catch((error) => {
// Error
});
};
让我知道我在这里能做什么,我对React相对陌生,总是想学习新东西。
尝试这种方法:
向组件添加error
状态:
state = {
email : "",
password : "",
error : false,
errMsg : ""
};
然后在handleSubmit
:内的firebase auth操作引发错误时更改它
.catch((error) => {
this.state = {error : true, errMsg: error.msg};
});
最后,添加一个条件TextField来显示错误消息:
{error && <TextField
error
id="yourErrorId"
helperText=this.state.errMsg
variant="outlined"
/>}
为错误创建一个状态:
state = {
email : "",
password : "",
error:"",
};
捕捉错误时更改:
.catch((error) => {
this.setState({error: error.response.data}) // change it to your error response
});
你的输入应该是这样的:
<FormControl error={error}>
<InputLabel htmlFor="email">Email</InputLabel>
<Input
id="email"
value={email}
onChange={this.handleChange}
aria-describedby="email"
/>
<FormHelperText id="email"> {error ? error : "Enter your email address"}</FormHelperText>
</FormControl>
请记住使用handleChange清除错误状态。