React中如何在父组件App的两个子组件间实现输入输出传递?
Absolutely you can! This is a classic scenario where you’ll use state lifting in React—since sibling components (Input and Output here) don’t have a direct way to share data, their parent component (App) will act as the central middleman to manage shared state and pass data/functions between them.
Here’s how to adjust your code to make this work:
Step 1: Add state to the parent App component
The App component will hold the input value state and provide a function to update that state.
Step 2: Pass the update function to the Input component
The Input component will use this function to send the user’s input back up to App.
Step 3: Pass the current state value to the Output component
The Output component will receive this value as a prop and display it.
Here’s the complete working code:
import React, { Component } from 'react'; class App extends Component { // Initialize state to store the input value state = { inputValue: '' }; // Function to update state when input changes handleInputChange = (value) => { this.setState({ inputValue: value }); }; render() { return ( <div className="app-container"> {/* Pass the update handler to Input as a prop */} <Input onInputChange={this.handleInputChange} /> {/* Pass the current input value to Output as a prop */} <Output displayValue={this.state.inputValue} /> </div> ); } } // Input component: uses the passed handler to send input up to App const Input = ({ onInputChange }) => { return ( <input type="text" onChange={(e) => onInputChange(e.target.value)} placeholder="Type something..." /> ); }; // Output component: displays the value received via props const Output = ({ displayValue }) => { return ( <div className="output"> You typed: <strong>{displayValue}</strong> </div> ); }; export default App;
How this flow works:
- When the user types in the Input component’s field, the
onChangeevent fires, and we call theonInputChangeprop (passed from App) with the current input value. - App updates its
inputValuestate with this new value. - Since Output receives
displayValuedirectly from App’s state, it automatically re-renders with the updated value whenever the state changes.
This pattern is fundamental in React for syncing sibling components—keeping state in the closest common parent ensures all dependent components stay in lockstep with the latest data.
内容的提问来源于stack exchange,提问作者thierved

