javascript Redux-form样本样板代码#reducex-form

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Redux-form样本样板代码#reducex-form相关的知识,希望对你有一定的参考价值。

import React, { Component } from "react";
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import {connect} from 'react-redux';
import {createPost} from '../actions';

class PostsNew extends Component {
	renderField(field) {
		const { meta: { touched, error } } = field; //ES6 destructuring
		const className = `form-group ${touched && error ? 'has-danger' : ''}`;

		return (
			<div className={className}>
				<label>{field.label}</label>
				<input 
					className="form-control"
					type="text"
					{...field.input} //just fancy JSX syntax(pre-generating event handlers) for wiring up multiple event handlers instead of doing: onChange={field.input.onChange} onFocus={field.input.onFocus}....and so on
				/>
				<div className="text-help">
					{ touched ? error : '' }
				</div>
			</div>
		);
	}

	onSubmit(values) {
		
		this.props.createPost(values, () => {
			this.props.history.push('/');
		});
	}

	// methods
	render() {
		const { handleSubmit } = this.props; //handleSubmit runs the redux-form side of things. Then if everything looks good, it runs the onSubmit function and we put our data processing there.

		return (
			<form onSubmit={handleSubmit(this.onSubmit.bind(this))}> 
				<Field 
					label="Title for Post" //note: you can always put any property as you like to name(e.g. labelForDisplay). And it will be accessible in renderField as one of its properties. Just keep in mind to use the component props all the time.
					name="title" 
					component={this.renderField}
				/>
				<Field 
					label="Categories"
					name="categories"
					component={this.renderField}
				/>
				<Field 
					label="Post Content"
					name="content"
					component={this.renderField}
				/>				
				<button className="btn btn-primary" type="submit">Submit</button>
				<Link className="btn btn-danger" to="/">
					Cancel
				</Link>

			</form>
		);
	}
}

function validate(values) {
	const errors = {}
	if (!values.title) {
		errors.title = 'Enter a title';
	}
	if (!values.categories) {
		errors.categories = 'Enter some categories';
	}
	if (!values.content) {
		errors.content = 'Enter some content';
	}

	//if errors is empty, the form is fine to submit
	//if errors has *any* properties, redux form assumes form is invalid
	return errors;
}


export default reduxForm({
	validate: validate,
	form: 'PostsNewForm'
})(
	connect(null, { createPost })(PostsNew)
);






以上是关于javascript Redux-form样本样板代码#reducex-form的主要内容,如果未能解决你的问题,请参考以下文章

MEANJS 样板:在哪里包含自定义 javascript 文件?

javascript 匿名函数样板

javascript hackerearch js样板

javascript React类组件样板

javascript 幻影开发样板

javascript Redux容器样板#redux