1

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

这是代码:

登录.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}}但都抛出了错误。

4

0 回答 0