刚刚创建此表单作为教程的一部分。但是,每当我提交表单时,我的控制台日志都会显示 undefined
。我做错了什么?
import React, {Component} from 'react';
import { reduxForm } from 'redux-form';
class Signin extends Component {
handleFormSubmit({email, password}) {
console.log(email); // this gives me 'undefined'
}
render() {
const {handleSubmit, fields: {email, password}} = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<fieldset className="form-group">
<label>Email:</label>
<input {...email} className="form-control" />
</fieldset>
<fieldset className="form-group">
<label>Password:</label>
<input {...password} className="form-control" />
</fieldset>
<button action="submit" className="btn btn-primary">Sign in</button>
</form>
);
}
}
export default reduxForm({
form: 'signin',
fields: ['email', 'password']
})(Signin);
最佳答案
这是由于 redux-form 的更新所致。
我们不是从 this.props
导入 {email,password}
的值,而是使用从 redux-form 导入的 Field
组件.
从 'redux-form' 导入 { Field, reduxForm };
然后使用它代替您拥有的 input
标签:
<fieldset className="form-group">
<label>Email:</label>
<Field
name="email"
className="form-control"
component="input"
type="text"
placeholder="Email"
/>
</fieldset>
此输入与 redux-form 的连接现在来自 name
属性,而不是从 this.props
中提取
重要注意事项:名称必须与字段中的名称相同:reduxForm 中定义的 [] 数组:
export default reduxForm({
form: 'signin',
fields: ['email', 'password']
})(Signin);
<小时/>
在此基础上,如果您想自定义字段使用的组件,您可以非常轻松地定义自己的自定义组件。
您可以定义一个函数,而不是向 Field 的组件属性提供字符串:
<div className="form-group">
<label>Last name:</label>
<Field type="text" className="form-control" placeholder="Smith" name="lastName"
component={textField} />
</div>
textField 是从另一个文件导入的:import {textField} from '../../redux_form_elements';
文本字段如下:
import React from 'react';
export const textField = (field) => (
<div>
<input className="form-control" {...field.input} type={field.type} placeholder={field.placeholder} />
{field.meta.touched && field.meta.error &&
<label id="basic-error" className="validation-error-label">This field is required.</label>
}
</div>
);
关于javascript - 简单的 Redux-Form 组件返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48734542/