我的表单不接受用户的输入值



我有一个用react strap创建的登录表单。我面临输入值问题,该表单在第一次输入电子邮件时表现为只读,但接受第二次输入密码。我曾尝试删除电子邮件字段以跟踪密码字段是否无法接受输入,但效果很好我已经附上了我的组件代码,请允许我感谢任何可以帮助解决这个问题的人

import React, { Component } from 'react';
import { Button, Card, CardBody, Col, Container, Form, Input, InputGroup, Row } from 
'reactstrap';  
import './Login.css'
class Login extends Component {
constructor(props) {
super(props)
this.state = {
email:'',
password:''
}
}
changeHandler = (e) =>{
this.setState({[e.target.name]:e.target.value });
}
onSubmit = (e) =>{
e.preventDefault();
fetch('http://localhost:5000/user/login',{
method:'POST',
body:JSON.stringify(this.state),
})
.then(response =>{
if(response.status === 200){
this.props.history.push('/')
}else{
const error = new Error(response.error);
throw error;
}
})
.catch(err=>{
console.error(err);
alert('Ooops! Login failed please check your email and password, then try again')
})
}
render() {
return (
<div className="app flex-row align-items-center">
<Container className="container">
<Row className="justify-content-center">
<Col md="12" lg="10" xl="8">
<Card className="mx-4">
<CardBody className="p-4">
<Form  onSubmit={this.onSubmit} className="login-form">
<h1>Login Form</h1>
<InputGroup className="mb-3">
<Input type="email " 
name="email " 
required="required"
placeholder="email "
value={this.state.email }
onChange={this.changeHandler}
/>
</InputGroup>
<InputGroup className="mb-3">
<Input type="password" 
name="password" 
required="required"
placeholder="Password"
value={this.state.password}
onChange={this.changeHandler}
/>
</InputGroup> 
<Row>
<Col xs="12" sm="6">
<Button type="submit"  className="btn btn-info mb-1" block><span>Login</span>
</Button>
<a href="/">Home</a>
</Col>
</Row>
</Form>
</CardBody>
</Card>
</Col>
</Row>
</Container>
</div>
)
}
}
export default Login;

问题是您的输入名称中有一个空格:

<Input type="email " 
name="email "
^ remove this space

因此,您的更改处理程序无法设置状态,因为它设置的是"电子邮件"而不是"电子邮件"。

您的输入类型和占位符中也有一个空格。

问题可能在changeHandler中。当你把它传给像这样的输入时

onChange={this.changeHandler}

中的this

changeHandler = (e) =>{
this.setState({[e.target.name]:e.target.value });
}

是指输入,而不是Class组件,因此它不更新state

要解决此问题,您应该将Class组件this绑定到changeHandler

constructor(props) {
super(props);
this.state = {
email:'',
password:''
}
this.changeHandler = this.changeHandler.bind(this);
}

你也可以阅读这篇文章。

最新更新