Reactjs 在输入时不改变反应状态
我正在尝试使用React、Typescript和AntDesign构建一个简单的登录/注册表单。 这是我的组成部分:Reactjs 在输入时不改变反应状态,reactjs,typescript,antd,Reactjs,Typescript,Antd,我正在尝试使用React、Typescript和AntDesign构建一个简单的登录/注册表单。 这是我的组成部分: import React, { Component } from 'react' import { Typography, Form, Input, Button } from 'antd'; const { Title } = Typography; interface Props { } interface State { email: string,
import React, { Component } from 'react'
import { Typography, Form, Input, Button } from 'antd';
const { Title } = Typography;
interface Props {
}
interface State {
email: string,
password: string
}
export class Login extends Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
email: '',
password: ''
}
}
handleChange = (e:React.FormEvent<HTMLInputElement>):void => {
e.preventDefault()
const { name, value } = e.currentTarget;
this.setState({ [name] : value } as Pick<State, keyof State> );
}
render() {
return (
<div>
<Title level={2}>Log In</Title>
<Form className='login-form'>
<Form.Item>
<Input size='large' placeholder='E-mail used during registration' name='email' onChange={this.handleChange} />
</Form.Item>
<Form.Item>
<Input size='large' type='password' placeholder='Password' name='password' onChange={this.handleChange} />
</Form.Item>
<Form.Item>
<Button size='large' type='primary' block>
Log In
</Button>
</Form.Item>
</Form>
</div>
)
}
}
问题是输入不会改变状态。
在React开发工具中,状态显示不变,但出现撤消符号。实际上,它确实有效。
Chrome开发工具一定有问题。我尝试console.logthis.state onBlur,它确实给出了预期的结果 我只是试着把它快速地放到我的项目中。尝试将您的结构更改为:
....
state: State = {
email: '',
password: ''
}
handleChange = (e: React.FormEvent<HTMLInputElement>): void => {
e.preventDefault()
const { name, value } = e.currentTarget;
this.setState({ [name]: value } as Pick<State, keyof State>, () => console.log(this.state));
}
....
基本上,我只是删除了构造函数,直接设置状态并键入它。
注意,我使用setState回调钩子检查状态是否实际更新
呈现:
和控制台日志:
如果任何人都无法从该问题中学到任何东西,您可以删除该问题。除此之外,您使用的是非受控组件,因此无需设置状态。或者您应该使用受控组件。