React -这在React中看起来如何?

wgeznvg7  于 2022-11-25  发布在  React
关注(0)|答案(1)|浏览(125)

我今天开始学习react,并且仍然试图弄清楚这个庄严的东西,有人能帮助我并且分享一下这个简单的代码在react中会是什么样子吗?从js规则到react的转换对我来说仍然有点困难。
提前感谢,祝您度过愉快的一天/一夜。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <input type="text" id="inp1" /> + <input type="text" id="inp2" />
    <div id="results">=</div>
    <button onclick="myFunction()">Add</button>
    <script>
      myFunction = () => {
        const num1 = parseInt(inp1.value);
        const num2 = parseInt(inp2.value);
        const res = num1 + num2;
        document.getElementById("results").innerHTML =
          "= The sum of " + num1 + " and " + num2 + " is: " + res;
      };
    </script>
  </body>
</html>
hi3rlvi2

hi3rlvi21#

import React, { useState } from "react";

export default function App() {

  const [num1, setNum1] = useState(null);
  const [num2, setNum2] = useState(null);

  const [result, setResult] = useState(null);

  const myFunction = () => {
    setResult(parseInt(num1, 10) + parseInt(num2, 10));
  }

  return (
    <div>
      <input type="number" onChange={(e) => setNum1(e.target.value)} />
      +
      <input type="number" onChange={(e) => setNum2(e.target.value)} />
      {
        result && <div>The sum of {num1} and {num2} is : {result}</div>
      }
      <button onClick={() => myFunction()}>Add</button>
    </div>
  )
}

相关问题