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

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.

  1. Remove the local state from Nav and rely on props from App instead
  2. Pass App's handleChange function to Nav, so the input can update App's state directly
  3. Keep passing App's userInput state to Content for 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:

  • Nav no longer has its own userInput state—it uses the value passed down from App via props.
  • The input in Nav now calls App's handleChange function, so every keystroke updates App's state directly.
  • Both Nav and Content now use the same single source of truth (from App's state), so their displayed values will always stay in sync.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:38:11