React - 使用 onClick 将新值从输出组件传递到输入字段

React - Passing a new value to an input field from an output component with an onClick

我需要能够在单击按钮时将输出值输入到新的输入字段中,但我不清楚如何实现这一点。我是 React 的新手,使用带有 react hooks 的功能组件,比如 useState。

我不确定如何编写 handleClick 函数,以便在单击按钮时新输入组件可以具有在输出组件中计算和显示的值。

到目前为止,这是我的准系统代码:

import React, {useState} from 'react';
import Output from "./Output.js"

export default function Calculator() {
  const [number1, setNumber1] = useState (0); 
  const [number2, setNumber2] = useState (0); 


  return (
    <div>

      <input id="first-number" value={number1} type="number" onChange={e => setNumber1(+e.target.value)}/>
      <input id="second-number" value={number2} type="number" onChange={e => setNumber2(+e.target.value)}/>

      <Output value={number1+number2}/>


      <button onClick={handleClick}>Click Here</button>

      <input id="new-input" />

    </div>
  )
}

我的输出组件:

import React from "react";

const Output = (props) => {
  return (
   <div className="outpout-box">
    {props.value}
   </div>
  )
}

您可以使用其他状态,例如 result:

export default function Calculator() {
  const [number1, setNumber1] = useState (0); 
  const [number2, setNumber2] = useState (0); 
  const [result, setResult] = useState(number1 + number2);

  const handleClick = event => {
    setResult(number1 + number2)
  }

  return (
    <div>

      <input id="first-number" value={number1} type="number" onChange={e => setNumber1(+e.target.value)}/>
      <input id="second-number" value={number2} type="number" onChange={e => setNumber2(+e.target.value)}/>

      <Output value={result}/>


      <button onClick={handleClick}>Click Here</button>

      <input id="new-input" />

    </div>
  )
}