如何不指定名称获取Redux Dynamic Form表单值(JSON生成表单)
Hey there! I totally get what you're aiming for—you want to collect all your form field values into a clean {"elementname1":"value1", "elementname2":"value2"} object when submitting, without having to manually specify each field name (like you did with formValueSelector). Let's go over two reliable ways to make this happen, depending on whether you're using plain React or Redux-Form (since you mentioned formValueSelector, I'm guessing Redux-Form is in play).
Approach 1: Plain React (No External Libraries)
If you're building the form without a form library, you can use a React ref to access the form element directly, then iterate through its fields to build your desired object. This works great for dynamically generated forms from JSON.
Example Code
import React, { Component, createRef } from 'react'; class DynamicForm extends Component { // Create a ref to reference the form element formRef = createRef(); handleSubmit = (e) => { e.preventDefault(); const formData = {}; const formElements = this.formRef.current.elements; // Loop through all form elements to build the key-value object for (let i = 0; i < formElements.length; i++) { const element = formElements[i]; // Skip elements without a name or submit buttons if (element.name && element.type !== 'submit') { // Handle special input types like checkboxes formData[element.name] = element.type === 'checkbox' ? element.checked : element.value; } } // Now you have your desired object! Use it to call your API console.log('Form Data:', formData); // apiCall(formData); }; render() { // Assume this JSON data is how you generate your form fields const formFieldsFromJSON = [ { name: 'elementname1', type: 'text', label: 'First Field' }, { name: 'elementname2', type: 'email', label: 'Email' }, { name: 'elementname3', type: 'checkbox', label: 'Agree to Terms' } ]; return ( <form ref={this.formRef} onSubmit={this.handleSubmit}> {formFieldsFromJSON.map(field => ( <div key={field.name} className="form-group"> <label htmlFor={field.name}>{field.label}</label> {field.type === 'checkbox' ? ( <input type={field.type} name={field.name} id={field.name} /> ) : ( <input type={field.type} name={field.name} id={field.name} className="form-control" /> )} </div> ))} <button type="submit" className="btn btn-primary">Submit</button> </form> ); } } export default DynamicForm;
Approach 2: Using Redux-Form (Since You Mentioned formValueSelector)
If you're using Redux-Form, you don't need to use formValueSelector for each field. Instead, use the getFormValues selector to grab the entire form's value object in one go.
Example Code
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { reduxForm, getFormValues } from 'redux-form'; class ReduxDynamicForm extends Component { handleSubmit = (formValues) => { // formValues is exactly the key-value object you want! console.log('Redux Form Values:', formValues); // Call your API here with formValues // apiCall(formValues); }; render() { const { handleSubmit } = this.props; // Your JSON-generated form fields const formFieldsFromJSON = [ { name: 'elementname1', type: 'text', label: 'First Field' }, { name: 'elementname2', type: 'password', label: 'Password' }, { name: 'elementname3', type: 'number', label: 'Age' } ]; return ( <form onSubmit={handleSubmit(this.handleSubmit)}> {formFieldsFromJSON.map(field => ( <div key={field.name} className="form-group"> <label htmlFor={field.name}>{field.label}</label> <input type={field.type} name={field.name} id={field.name} className="form-control" // Spread Redux-Form's input props to connect the field {...this.props.input} /> </div> ))} <button type="submit" className="btn btn-primary">Submit</button> </form> ); } } // Map state to props to get the full form values const mapStateToProps = (state) => ({ // Replace "yourUniqueFormName" with the name you used in reduxForm() fullFormValues: getFormValues('yourUniqueFormName')(state) }); // Wrap the component with reduxForm ReduxDynamicForm = reduxForm({ form: 'yourUniqueFormName' // This name must match the one in getFormValues })(ReduxDynamicForm); // Connect to Redux store export default connect(mapStateToProps)(ReduxDynamicForm);
Quick Note
If you're using a different form library like Formik, the idea is similar—you can access the full values object directly from the form hook or component props without manually selecting each field.
内容的提问来源于stack exchange,提问作者Lakshmi Prasanna

