反应状态不改变输入

时间:2019-09-26 09:19:08

标签: 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,
    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 Devtools中,状态保持不变,但出现undo符号。

2 个答案:

答案 0 :(得分:0)

我只是尝试将其快速弹出到我的项目中。尝试将您的结构更改为此:

    ....
    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()回调钩子来检查状态是否实际更新。

渲染: The App

和控制台日志: enter image description here

答案 1 :(得分:-2)

实际上,它确实有效。 Chrome Devtools一定有问题。我尝试console.log(this.state) onBlur,它确实给出了预期的结果。

相关问题