You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React表单提交时如何将表单数据传递至其他组件?

How to Pass Form Data to Another Component in React (And Is Context the Best Fit?)

Great question! Let's break this down clearly, based on your component code and common React patterns.

First: Can You Pass Form Data to Another Component on Submit?

Absolutely! There are several standard ways to do this in React, and the best choice depends on how your components are structured and how widely you need to share this form data.

Is Context the Best Solution Here?

Short answer: It depends. Context is ideal when you need to share data across multiple unrelated components or through deeply nested component trees (to avoid "props drilling"). But if you only need to pass data to a nearby component (like a sibling or direct parent/child), using plain props is simpler and more straightforward.

Let's walk through the most common approaches with code examples tailored to your Form component.


Approach 1: Props + Callback (Best for Nearby Components)

If the component that needs the form data is a direct parent, sibling, or close relative, this is the easiest approach. You'll add a callback prop to your Form component, then invoke it with the form data when the form submits.

Modified Form Component

class Form extends Component { 
  // ... (keep your existing constructor and handleChange methods)

  handleFormSubmit(event){ 
    event.preventDefault(); 
    // Pass the form data up to the parent via the callback prop
    this.props.onFormSubmit(this.state);
    alert(`${this.state.username} ${this.state.comments} ${this.state.topic}`); 
  } 

  render() { 
    return ( 
      // ... (keep your existing form JSX)
    ) 
  } 
}

Usage in Parent Component

Now, in the parent component that renders both your Form and the component needing the data (e.g., a ResultsDisplay component), you'll handle the callback and pass the data down:

class ParentComponent extends Component {
  state = { submittedFormData: null };

  handleFormSubmission = (formData) => {
    this.setState({ submittedFormData: formData });
  };

  render() {
    return (
      <div>
        <Form onFormSubmit={this.handleFormSubmission} />
        {/* Pass the submitted data to the other component */}
        {this.state.submittedFormData && (
          <ResultsDisplay data={this.state.submittedFormData} />
        )}
      </div>
    );
  }
}

Approach 2: Context API (Best for Cross-Component Sharing)

If you need the form data to be accessible by many components across different parts of your app (or through deep nesting), Context is a great fit. Here's how to implement it with your form:

Step 1: Create the Context

import React, { Component, createContext } from 'react';

// Create a context to hold form data
const FormDataContext = createContext();

// Create a Provider component to wrap your app (or relevant section)
class FormDataProvider extends Component {
  state = { submittedFormData: null };

  setSubmittedFormData = (data) => {
    this.setState({ submittedFormData: data });
  };

  render() {
    return (
      <FormDataContext.Provider
        value={{
          submittedFormData: this.state.submittedFormData,
          setSubmittedFormData: this.setSubmittedFormData
        }}
      >
        {this.props.children}
      </FormDataContext.Provider>
    );
  }
}

Step 2: Update Your Form Component to Use the Context

class Form extends Component { 
  // ... (keep your existing constructor and handleChange methods)

  // Get the context method to set form data
  static contextType = FormDataContext;

  handleFormSubmit(event){ 
    event.preventDefault(); 
    // Use the context method to share the data
    this.context.setSubmittedFormData(this.state);
    alert(`${this.state.username} ${this.state.comments} ${this.state.topic}`); 
  } 

  render() { 
    return ( 
      // ... (keep your existing form JSX)
    ) 
  } 
}

Step 3: Consume the Context in Another Component

Any component that needs the form data can now access it directly via the context:

class ResultsDisplay extends Component {
  static contextType = FormDataContext;

  render() {
    const { submittedFormData } = this.context;
    if (!submittedFormData) return <p>No form data submitted yet!</p>;

    return (
      <div>
        <h3>Submitted Data:</h3>
        <p>Username: {submittedFormData.username}</p>
        <p>Comments: {submittedFormData.comments}</p>
        <p>Topic: {submittedFormData.topic}</p>
      </div>
    );
  }
}

Step 4: Wrap Your App with the Provider

Make sure to wrap the part of your app that needs access to the form data with the provider:

// In your root component (e.g., App.js)
function App() {
  return (
    <FormDataProvider>
      <div className="App">
        <Form />
        <ResultsDisplay />
      </div>
    </FormDataProvider>
  );
}

Approach 3: State Management Libraries (For Complex Apps)

If your app has lots of global state to manage (beyond just this form), libraries like Redux, Zustand, or Recoil might be worth considering. These are overkill for simple form data sharing, but they shine in large, complex applications.

Final Recommendations

  • Use props + callback if you're only passing data to a nearby component (sibling, parent, or direct child). It's simple, easy to debug, and requires no extra setup.
  • Use Context API if you need to share the form data across multiple unrelated components or through deep nesting.
  • Use a state management library only if your app has extensive global state needs.

内容的提问来源于stack exchange,提问作者Ciaran Whyte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:29:53