在 raect js 中,我该怎么做,修复 React 代码以在组件之间传递数据

问题描述 投票:0回答:0

描述:给定的 React 代码在组件之间传递数据时存在问题。 App 组件没有将计数器状态传递给 Statetutorial 组件,Statetutorial 组件无法在 App 组件中设置下注状态。通过将 setBetValue 函数作为 prop 从 App 组件传递到 Statetutorial 组件,并在调用增量函数时使用它在 App 组件中设置投注状态来修复代码。

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

export default function App(props) {
  const [counter, setCounter] = useState(0);

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

  return (
    <div>
      <h1>Hello Fello</h1>
      <div>{counter}</div>
      <button onClick={increment}>increment</button>
      <Statetutorial />
      <br /> <br /> <br />
    </div>
  );
}

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

  const onChange = (event) => {
    const newValue = event.target.value;
    setBet(newValue);
  };

  return (
    <>
      {props.counter}{bet} 
      <input placeholder="type" onChange={onChange} />
    </>
  );
}

我的输出不是我需要的。我想在 Statetutorial 里面渲染 App 数据

node.js reactjs react-hooks
© www.soinside.com 2019 - 2024. All rights reserved.