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

React组件数据传递修复:如何在Statetutorial中渲染App组件状态?

修复React组件间数据传递问题

问题根源

原代码中App组件未将自身的counter状态作为属性传递给Statetutorial子组件,导致子组件无法通过props.counter获取并渲染该值;同时子组件的bet状态仅在内部维护,父组件无法感知或修改。

修复后的完整代码

import React, { useState } from 'react';
import './style.css';

export default function App(props) {
  const [counter, setCounter] = useState(0);
  // 新增父级bet状态,用于同步子组件的输入值
  const [parentBet, setParentBet] = useState('');

  const increment = () => {
    const newCounter = counter + 3;
    setCounter(newCounter);
  };

  // 定义回调函数,接收子组件传递的bet值并更新父级状态
  const syncBetToParent = (newBetValue) => {
    setParentBet(newBetValue);
  };

  return (
    <div>
      <h1>Hello Fello</h1>
      <div>{counter}</div>
      <button onClick={increment}>increment</button>
      {/* 传递counter属性给子组件,同时传递同步bet的回调 */}
      <Statetutorial counter={counter} onBetChange={syncBetToParent} />
      <br /> <br /> <br />
      {/* 可选:在父组件中展示同步后的bet值 */}
      <div>父组件同步的bet值:{parentBet}</div>
    </div>
  );
}

export function Statetutorial(props) {
  const [bet, setBet] = useState('');

  const onChange = (event) => {
    const newValue = event.target.value;
    setBet(newValue);
    // 调用父组件传递的回调,将最新bet值同步过去
    props.onBetChange(newValue);
  };

  return (
    <>
      {/* 现在可正常渲染父组件传递的counter */}
      {props.counter}
      {bet} 
      <input placeholder="type" onChange={onChange} />
    </>
  );
}

关键修改点

  • 传递counter状态:在App组件中调用Statetutorial时,添加counter={counter}属性,子组件通过props.counter即可获取并渲染父组件的counter值。
  • 同步bet状态:父组件定义syncBetToParent回调函数并传递给子组件,子组件在输入变化时调用该回调,将内部bet值同步到父组件,解决父组件无法操作子组件bet状态的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:23:21