react封装form受控组件

页面中多个表单,多个输入框,统一封装处理,formCreate为一个高阶组件

import React from 'react';

export const formCreate = WrappedComponent => class extends React.Component {
    
    constructor(){
		super();
		this.state={fields:{}}
	}
 
	onChange = key => e =>{
		const { fields } = this.state;
		fields[key] = e.target.value;
		this.setState({
			fields,
		});
	}
 
	handleSubmit=()=>this.state.fields
 
	getField = fieldName =>{
		return {
			onChange:this.onChange(fieldName)
		}
	}
 
	render(){
		const props = {
			...this.props,
			getVal:this.handleSubmit,
			setval:this.getField,
		}
 
		return()
	}

};

使用:

import { formCreate } from '../../components/formCreat';

@formCreate
export default class Login extends React.Component {
...//省略代码


立即登录
handleSubmit=()=>{
		console.log(this.props.getVal())//这里就是需要的值{name:1111,password:2222}
	}
......//省略代码

你可能感兴趣的:(js,react,react受控组件,react高阶组件)