我有一个已经构建的React表单,它可以很好地运行期望重置功能。它以不同的方式使用不受控制的组件。我正在寻找我需要遵循的内容,更改代码以实现我的目标。
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
import * as React from "react";
import WidgetComponent from './../../lib/WidgetComponent';
import jQuery from 'jquery';
import InputListComponent from './components/InputListComponent';
import FormInputComponent from './components/FormInputComponent';
import formTextInputComponent from './components/formTextInputComponent';
import FormInputPasswordComponent from './components/FormInputPasswordComponent';
import FormSelectComponent from './components/FormSelectComponent';
import SubmitBtnListComponent from './components/SubmitBtnListComponent';
import SubmitBtnComponent from './components/SubmitBtnComponent';
import ErrorListBox from './components/ErrorListBox';
import EmailPromptModal from './components/EmailPromptModal';
import formHandlerInterfaceFactory from './lib/formHandlerInterface';
import formValidator from './lib/formValidators';
import {generateJQueryAjaxConfigFromPlaceholders} from './../../lib/GenerateJQueryAjaxConfig';
import './styles/registration-form.scss';
export default class ControlPanelCreateAccounts extends WidgetComponent {
constructor(props) {
super(props);
this.state = {
form: {
firstName: "",
lastName: "",
username: "",
password: "",
confirmPassword: "",
email: "",
phone: "",
accessLevel: -1,
},
userRoles: [],
validInputs: {
firstName: false,
lastName: false,
username: false,
password: false,
confirmPassword: false,
email: false,
phone: false,
accessLevel: false,
},
defaultValue: {
firstName: "",
lastName: "",
username: "",
password: "",
confirmPassword: "",
email: "",
phone: "",
accessLevel: -1,
},
errors: [],
submitService: null,
userRoleService: null,
newUserId: null,
};
this.onFormInputChange = this.onFormInputChange.bind(this);
this.onServicesCalled = this.onServicesCalled.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
this.formElementInvalid = this.formElementInvalid.bind(this);
this.formElementValid = this.formElementValid.bind(this);
this.postWidgetLoad = this.postWidgetLoad.bind(this);
this.createUserRequest = this.createUserRequest.bind(this);
this.createUserRoleRequest = this.createUserRoleRequest.bind(this);
this.onResetReceived = this.onResetReceived.bind(this);
this.onFormInputReset = this.onFormInputReset.bind(this);
}
onResetReceived(){
console.log('onResetReceived');
let newState = Object.assign(this.state.form, {
firstName : "",
});
this.setState(newState);
console.log(this.state.form);
}
postWidgetLoad(widget) {
EmailPromptModal.service = widget.services[2];//??
let submitService = widget.services[1];//1
let userRoleService = widget.services[2];//2
//this.storeState({ submitService });
let newState = Object.assign(this.state, {
submitService: submitService,
userRoleService: userRoleService
});
this.setState(newState);
}
validate() {
console.log('validating pre-submit');
let errors = Object.keys(this.state.validInputs).reduce((accum, current) => {
console.log('state of accumulator is: ');
console.log(accum);
console.log('current iteration is: ' + current);
//console.log('password and reType passwords are : ');
//console.log(this.state.form.password + " :: " + this.state.confirmPassword );
if (this.state.validInputs[current] === false) {
console.log('current input is invalid');
this.validate = this.validate.bind(this);
if (current === 'firstName') {
accum.push('The first name field is either empty or contains invalid characters');
}
if (current === 'lastName') {
accum.push('The last name field is either empty or contains invalid characters');
}
if (current === 'email') {
accum.push('The email field is empty or is not a valid email address');
}
if (current === 'phone') {
accum.push('The phone field is empty or is not a valid phone number');
}
if (current === 'password') {
accum.push('The password field is empty or contain less than 5 characters or contain invalid character');
}
if (current === 'confirmPassword') {
accum.push('The passwords mismatched');
}
if (current === 'accessLevel') {
accum.push('You must select a accessLevel from the drop-down menu.');
}
}
return accum;
}, []);
console.log('final error list looks like: ');
console.log(errors);
this.storeState({
errors: errors
});
return errors.length === 0;
}
onServicesCalled() {
let response = arguments[0][0].data;
let roleList = [];
if (response) {
response.map(element => {
roleList.push({val: element.id, text: element.role_name});
});
}
let newState = Object.assign(this.state, {
userRoles: roleList
});
this.setState(newState);
}
onFormInputChange(ev, legend) {
let value = ev.target.value;
let form = this.state.form;
form[legend] = value;
this.storeState({
form
});
formElementInvalid(elem) {
let name = elem.name;
let stateUpdateObj = this.state.validInputs;
stateUpdateObj[name] = false;
this.storeState({validInputs: stateUpdateObj});
if (name !== 'status') {
elem.classList.add('input-error');
} else {
document.getElementById('status-error-field').classList.add('visible');
}
}
formElementValid(elem) {
let name = elem.name;
let stateUpdateObj = this.state.validInputs;
stateUpdateObj[name] = true;
this.storeState({validInputs: stateUpdateObj});
if (name !== 'status') {
elem.classList.remove('input-error');
} else {
document.getElementById('status-error-field').classList.remove('visible');
}
}
onFormSubmit() {
if (this.validate()) {
console.log("validate got passed");
console.log(this.state.form);
var id;
// match password fields
if (this.state.form.password !== this.state.form.confirmPassword) {
let stateUpdateObj = this.state.validInputs;
stateUpdateObj['confirmPassword'] = false;
this.storeState({validInputs: stateUpdateObj});
this.onFormSubmit();
} else {
jQuery.when(this.createUserRequest()).done((r) => {
console.log("submit for createUser is success reload!");
console.log(r);
id = r.data.id;
jQuery.when(this.createUserRoleRequest(id)).done((r) => {
console.log("submit for createUserRole is success reload!");
console.log(r);
if(r.data.wasSuccessful){
console.log("create UserRole is successful, So reload the table ");
// do page refresh here
window.pubsub.publish('isp.reload-control-users', {});
//reset the form
console.log("reset the form contents");
this.onResetReceived();
}
}).fail((xhr, status, error) => {
console.log(status);
console.error(error);
alert('An error occured while submitting this request, if this issue persists please contact support.');
});
let newState = Object.assign(this.state, {
newUserId: r.data.id
});
this.setState(newState);
}).fail((xhr, status, error) => {
console.log(status);
console.error(error);
alert('An error occured while submitting this request, if this issue persists please contact support.');
});
}
}
}
//create a record in is_auth_roles table
createUserRoleRequest(id) {
let config = generateJQueryAjaxConfigFromPlaceholders(this.state.userRoleService, {'userId': id});
config.headers['Content-Type'] = 'application/json';
config.headers['Accept'] = '*/*';
config.data = JSON.stringify({
'roleId': this.state.form.accessLevel,
'type': 'add'
});
console.log("submit config of createUserRoleRequest() is: ");
console.log(config);
return jQuery.ajax(config);
}
createUserRequest() {
let config = generateJQueryAjaxConfigFromPlaceholders(this.state.submitService, {});
config.headers['Content-Type'] = 'application/json';
config.headers['Accept'] = '*/*';
config.data = JSON.stringify({
firstName: this.state.form.firstName,
lastName: this.state.form.lastName,
username: this.state.form.username,
phone: this.state.form.phone,
password: this.state.form.password,
confirmPassword: this.state.form.confirmPassword,
email: this.state.form.email,
accessLevel: this.state.accessLevel
});
console.log("submit config is: ");
console.log(config);
return jQuery.ajax(config);
}
render() {
return (
<div className="registration-form">
<h3 className="component-title"><i className="fa fa-table" aria-hidden="true"></i> User <span> Registration</span></h3><br/>
<InputListComponent>
{/*onValid={this.formElementValid} />*/}
<formTextInputComponent legend="firstName" label="First Name" placeholder="First Name" onChange={this.onFormInputChange} validator={formValidator.nameValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.firstName} value={ this.state.value}
onValid={this.formElementValid} />
<FormInputComponent legend="lastName" label="Last Name" placeholder="Last Name" onChange={this.onFormInputChange} validator={formValidator.nameValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.lastName}
onValid={this.formElementValid}/>
<FormInputComponent legend="username" label="User Name" placeholder="User Name" onChange={this.onFormInputChange} validator={formValidator.nameValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.username}
onValid={this.formElementValid}/>
<FormInputPasswordComponent legend="password" label="Password" placeholder="Password" onChange={this.onFormInputChange} validator={formValidator.passwordValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.password}
onValid={this.formElementValid}/>
<FormInputPasswordComponent legend="confirmPassword" label="Confirm Password" placeholder="Confirm Password" onChange={this.onFormInputChange} validator={formValidator.passwordValidator} default = {this.state.defaultValue.confirmPassword}
onInvalid={this.formElementInvalid} onValid={this.formElementValid}/>
<FormInputComponent legend="email" label="Email Address" placeholder="Email" onChange={this.onFormInputChange} validator={formValidator.emailValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.email}
onValid={this.formElementValid}/>
<FormInputComponent legend="phone" label="Phone Number" placeholder="Phone Number" onChange={this.onFormInputChange} validator={formValidator.phoneValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.phone}
onValid={this.formElementValid}/>
<FormSelectComponent legend="accessLevel" data={this.state.userRoles} onChange={this.onFormInputChange} validator={formValidator.statusValidator} onInvalid={this.formElementInvalid} default = {this.state.defaultValue.accessLevel}
onValid={this.formElementValid}/>
</InputListComponent>
<ErrorListBox errorList={this.state.errors}/>
<button className="dataTable-modal-btn click-btn" onClick={this.onFormSubmit}>CREATE USER</button>
</div>
);
}
}
window.ControlPanelCreateAccounts = ControlPanelCreateAccounts;
window.CurrentWidget = window.ControlPanelCreateAccounts;
这是formInputComponent代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
const FormInputComponent = (props) => {
const onChangeHandler = (ev) => {
if(props.validator(ev.target.value)) {
props.onChange(ev, props.legend);
props.onValid(ev.target);
} else {
props.onInvalid(ev.target);
}
};
console.log('props.defaultValue');
console.log(props.legend);
console.log(props.default);
console.log(props.value);
return (
<div className="form-row">
<label>{props.label}</label><br />
<input name={props.legend} type="text" placeholder={props.placeholder} onChange={onChangeHandler} defaultValue={props.default || ''} value={props.value}/>
</div>
);
};
FormInputComponent.propTypes = {
legend: React.PropTypes.string,
label: React.PropTypes.string,
placeholder: React.PropTypes.string,
onChange: React.PropTypes.func,
validator: React.PropTypes.func,
onInvalid: React.PropTypes.func,
onValid: React.PropTypes.func,
default: React.PropTypes.string,
};
export default FormInputComponent;
答案 0 :(得分:0)
如果您希望setState
内的onResetReceived
重置表单,则需要设置每个表单字段的value
道具。 default
道具作为FormInputComponent
的{{1}}发送到defaultValue
,但您也可以看到它也接受input
(即使value={props.value}
1}}未在其value
中定义。来自父集
PropTypes
这将确保通过<FormInputComponent value={this.state.form.firstName} ... />
更改this.state.form
将更新每个表单字段。