React中如何将Nav组件输入值传递至Content组件?
Hey there! Let's break down why your props.userInput is coming through as undefined, and fix it step by step.
The core issue here is that you're managing input state twice—once in the App component, and once in the Nav component. Right now, when you type in the Nav input, it only updates its own local state, never telling the App component about the new value. Since Content gets its userInput from App's state (which never changes), it stays empty/undefined.
Here's how to fix it:
We'll use React's "state lifting" pattern—moving the single source of truth for the input value up to the common parent (App), then passing the necessary data and functions down to child components.
- Remove the local state from
Navand rely on props fromAppinstead - Pass
App'shandleChangefunction toNav, so the input can updateApp's state directly - Keep passing
App'suserInputstate toContentfor display
Fixed Code:
// 根组件 class App extends React.Component { constructor(props) { super(props); this.state = { userInput: '' }; } handleChange = (e) => { this.setState({ userInput: e.target.value }); }; render() { const { userInput } = this.state; return ( <div className="recipes"> {/* Pass state and handler to Nav */} <Nav userInput={userInput} handleChange={this.handleChange} /> {/* Pass updated state to Content */} <Content userInput={userInput} /> </div> ); } } // 存储输入框的Nav组件,现在使用父组件传递的状态和方法 class Nav extends React.Component { // 移除了Nav自己的local state render() { const { userInput, handleChange } = this.props; return ( <nav className="nav"> <h1 className="title">Nourish</h1> <h2 className="title">{userInput}</h2> {/* Use parent's handleChange to update App's state */} <input type="text" className="input" onChange={handleChange} /> </nav> ); } } // 用于展示输入值的Content组件 const Content = (props) => { console.log(props.userInput); return <h2 className="main">{props.userInput}</h2>; };
What changed:
Navno longer has its ownuserInputstate—it uses the value passed down fromAppvia props.- The input in
Navnow callsApp'shandleChangefunction, so every keystroke updatesApp's state directly. - Both
NavandContentnow use the same single source of truth (fromApp's state), so their displayed values will always stay in sync.
内容的提问来源于stack exchange,提问作者Alanaj

