在Redux表单的输入上设置新状态

时间:2016-05-19 07:51:15

标签: javascript reactjs redux-form

我在项目中使用Redux-Form并遇到了问题。我无法使用新的输入值设置state。

以下是代码:

login.js

import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
import _ from 'lodash';
import {
  FormGroup,
  FormControl,
  InputGroup,
  ControlLabel,
  Button
} from 'react-bootstrap';


const FIELDS = {
    username: {
        type: 'text',
        label: 'Username',
        id: 'username',
        icon: 'fa fa-user'
    },
    password: {
        type: 'password',
        label: 'Password',
        id: 'password',
        icon: 'fa fa-key'
    }
};

class Login extends Component {

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

    onSubmit() {
        console.log(`Username: ${this.state.username} Password: ${this.state.password}`);
    }
    onInputChange(event) {
        this.setState({
            username: event.target.value,
            password: event.target.value
        });
    }

    renderField(fieldConfig, field) {
        const fieldHelper = this.props.fields[field];

        return(
      <FormGroup controlId={fieldConfig.id}>
        <ControlLabel srOnly={true}>{fieldConfig.label}</ControlLabel>
        <InputGroup>
          <InputGroup.Addon>
            <i className={fieldConfig.icon}></i>
          </InputGroup.Addon>
          <FormControl type={fieldConfig.type} placeholder={fieldConfig.label} {...fieldHelper} value={this.state.fieldConfig} onChange={this.onInputChange.bind(this)} ></FormControl>
        </InputGroup>
        <span className='text-danger'>
            {fieldHelper.touched ? fieldHelper.error : ''}
          </span>
      </FormGroup>
        );
    }

    render() {
        const { handleSubmit } = this.props;
        return(
            <form className="mixForm col-sm-4" id="loginDiv" onSubmit={handleSubmit(props => this.onSubmit(props))} >
                {_.map(FIELDS, this.renderField.bind(this))}
                <Button type="submit" bsStyle="info" id="loginBtn">Log In</Button>
            </form>
        );
    }
}

function validate(values){
    const errors = {};

    _.each(FIELDS, (type, field) => {
        if(!values[field]) {
            errors[field] = `Enter a Valid ${field}`;
        }
    });
    return errors;
}

export default reduxForm({
    form: 'Login',
    fields: _.keys(FIELDS),
    validate
})(Login);

我想确保输入标记获得各自的状态。

如何动态执行此操作?我尝试使用value={this.state.fieldConfig.id}value={this.state.{fieldConfig.id}},但都犯了错误。

0 个答案:

没有答案