我正在尝试验证用户登录的电子邮件和密码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 : ""
};
然后从firebase auth操作中抛出错误时将其更改handleSubmit
:
.catch((error) => {
this.state = {error : true, errMsg: error.msg};
});
最后,添加条件TextField以显示错误消息:
{error && <TextField
error
id="yourErrorId"
helperText=this.state.errMsg
variant="outlined"
/>}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句