我正在尝试在 React 中制作一个表单,我对它非常陌生,并且我正在结合我观看的两个教程。 但是,当我尝试制作表单时,它没有显示。
formField.js
:
export default [
{ label: 'Title', name: 'contactTitle' },
{ label: 'First Name', name: 'contactName' },
{ label: 'Last Name', name: 'contactLastName' },
{ label: 'Email', name: 'contactEmail' },
{ label: 'Telephone', name: 'contactTelephone' },
{ label: 'Address', name: 'contactAddress' },
];
然后我有一个 ContactField.js
,我在其中创建表单的单个字段:
import React from 'react';
export default ({input, label, meta: {error, touched}}) => {
return (
<div>
<label>{label}</label>
<input {...input} style={{marginBottom: '5px'}} />
<div className="red-text" style={{marginBottom: '20px'}}>
{touched && error}
</div>
</div>
)
}
最后我得到了组件ContactNew.js
。页面上仅呈现我的 h2
和 button
,整个表单丢失:
import _ from 'lodash';
import React, { Component } from 'react';
import { Field, Form, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import ContactField from './ContactField';
import { createContact } from '../../actions';
import formField from './formField';
import validateEmails from '../../utils/validateEmail';
class ContactNew extends Component {
renderFields() {
return _.map(formField, ({ label, name }) => {
<Field
key={name}
component={ContactField}
type="text"
label={label}
name={name}
/>;
});
}
onSubmit(values) {
this.props.createContact(values, () => {
this.props.history.push('/');
});
}
render() {
const { handleSubmit } = this.props;
return (
<div>
<h3>Add new contact:</h3>
<Form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
{this.renderFields()}
<button className="waves-effect waves-light btn blue darken-1" type="submit">Save</button>
</Form>
</div>
);
}
}
function validate(values) {
const errors = {};
errors.contactEmail = validateEmails(values.contactEmail || '');
_.each(formField, ({ name }) => {
if (!values[name]) {
errors[name] = 'You must provide a value';
}
});
return errors;
}
export default reduxForm({
validate,
form: 'contactForm',
destroyOnUnmount: false
})(connect(null, { createContact })(ContactNew));
在我的操作
中,我有:
export function createContact(values, callback) {
const request = axios.post('/api/client', values)
.then(() => callback());
return {
type: CREATE_CONTACT,
payload: request
}
}
我不知道是否只有一个小错误没有渲染我的表单,或者全部都是错误的。我在控制台中没有收到任何错误。
最佳答案
renderFields
上存在语法错误。您没有从 map
返回创建的组件,并且在 FormField
末尾有一个额外的 ;
(分号)。请查看如何使用 map
lodash docs
应该是这样的
renderFields() {
return _.map(formField, ({ label, name }) => (
<Field
key={name}
component={ContactField}
type="text"
label={label}
name={name}
/>
));
}
关于javascript - 如何在 React 中渲染表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46390111/