Saya mencoba reaksi baru untuk fungsi tanpa kelas dan saya mencoba menggunakan setstate tetapi tidak berfungsi, mengatakan tidak terdefinisi jika saya menggunakannya langsung atau mengatakan itu bukan fungsi jika saya menghapus this. darinya.

Ini kode saya

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

function App() {
  var [sum1, setSum1] = useState(0);
  var [sum2, setSum2] = useState(0);

  function handleClick(props) {
    let buttonText = props.target.value;
    let inputText = document.getElementById('result').value;
    console.log(inputText + buttonText);
    // let sum1 =setState;
    // let sum2 =setState;
    
    
      let  total = inputText + buttonText;
        if (total.charAt(0) === "0") {
          
        } else {
          document.getElementById("result").value = total;
        }
        if (props.target.value === "clear") {
          document.getElementById("result").value = "";
        }
        if (props.target.value === "+") {
          sum1 =document.getElementById("result").value.slice(0, -1);
          setSum1({sum1:parseFloat(sum1)});
          // alert(sum1);
          document.getElementById("result").value = "";
          alert(sum1);
        }
        if (props.target.value === "=") {
          
            sum2 =document.getElementById("result").value.slice(0, -1);
            setSum2({sum2:parseFloat(sum2)});
            alert(sum1+sum2);
            document.getElementById("result").innerText = sum1+sum2;
          }
        return total;
  }
    
    
  
  // function handleClick2(props) {
  //   document.getElementById("ans").innerHTML = eval(document.getElementById("result").value);
  // }
  return (
    <div className="App">
          <div id="ans" className="answer">Ans = 0</div>
          <input type="text" onChange={handleClick} readOnly  placeholder="0" className="inputid" id="result"/>
           <hr/> 
           {/* calculator buttons below */}
           {/* button + */}
           <button className="opbut" value="+" onClick={handleClick}>+</button>
           {/* button - */}
           <button className="opbut" value="-" onClick={handleClick}>-</button>
           {/* button × */}
           <button className="opbut" value="*" onClick={handleClick}>×</button>
           {/* button ÷ */}
           <button className="opbut"  value="/" onClick={handleClick}>÷</button>
           {/* button 0 */}
           <button className="calbut" value={0} onClick={handleClick}>0</button>
           {/* button 1 */}
           <button className="calbut" value={1} onClick={handleClick}>1</button>
           {/* button 2 */}
           <button className="calbut" value={2}  onClick={handleClick}>2</button>
           {/* button 3 */}
           <button className="calbut" value={3} onClick={handleClick}>3</button>
           {/* button 4 */}
           <button className="calbut" value={4} onClick={handleClick}>4</button>
           {/* button 5 */}
           <button className="calbut" value={5} onClick={handleClick}>5</button>
           {/* button 6 */}
           <button className="calbut" value={6} onClick={handleClick}>6</button>
           {/* button 7 */}
           <button className="calbut" value={7} onClick={handleClick}>7</button>
           {/* button 8 */}
           <button className="calbut" value={8} onClick={handleClick}>8</button>
           {/* button 9 */}
           <button className="calbut"  value={9} onClick={handleClick}>9</button>
           {/* button ( */}
           <button className="opbut"  value="clear" onClick={handleClick}>C</button>
           {/* button ) */}
           <button className="opbut" value="Del" onClick={handleClick}>Del</button>
           {/* button % */}
           <button className="opbut" value="%" onClick={handleClick}>%</button>
           {/* button y^ */}
           <button className="opbut" value="^" onClick={handleClick}>y^</button>
           {/* button total = */}
           <button className="ansbut" value="=" onClick={handleClick}>=</button>
           <hr/>
           <div className="appName">A Simple React Calculator - Jayflo</div>
        </div>
  );
  
}

export default App;

Di atas adalah kodenya .... ketika saya mencoba memilih tombol, dan operator klik yang dipilih, atur dan hapus bidang teks kemudian terima input lain dan operasikan kedua input ...

-1
Mira BeeCalifonia 22 September 2021, 13:28

3 jawaban

Jawaban Terbaik

React memiliki cara khusus untuk memperbarui DOM berdasarkan status (nilai) elemen, jadi Anda tidak dapat menggunakan metode elemen asli.

Dalam contoh ini kami menggunakan tiga kait: useState, useEffect, dan useRef.

useState mempertahankan status elemen input, perhitungan yang diperbarui, dan evaluasi akhir yang diteruskan ke div hasil.

useEffect memastikan bahwa setelah hasilnya selesai, kami menghapus status calc.

useRef adalah cara React mengidentifikasi sebuah elemen. Dalam hal ini, setelah setiap tombol diklik, elemen input difokuskan lagi.

Berikut ini contoh kerja berdasarkan kode Anda.

const { useRef, useEffect, useState } = React;

function Example() {

  const [ input, setInput ] = useState('');
  const [ calc, setCalc ] = useState('');
  const [ result, setResult ] = useState('');
  
  const inputRef = useRef();

  // Update the input state when the value is changed
  function handleInput(e) {
    const { value } = e.target;
    setInput(value);
  }

  // When the input is no longer focused (we've clicked
  // a button) update the `calc` state
  function handleBlur(e) {
    const { value } = e.target;
    setCalc(prev => prev + value);
  }

  // When we click a button, either update the `calc` state,
  // or if we click "=", update the `result` state
  function handleClick(e) {
    const { nodeName, value } = e.target;
    if (nodeName === 'BUTTON') {
      setInput('');
      inputRef.current.focus();
      switch(value) {
        case '=': {
          setResult(eval(calc));
          break;
        }
        case 'clear': {
          setCalc('');
          break;
        }
        default: {
          setCalc(prev => prev + value);
          break;
        }
      }
    }
  }

  // When the result is updated, clear the `calc` state
  useEffect(() => setCalc(''), [result]);

  return (
    <div class="container">
      <div>
        <div>{`Result: ${result}`}</div>
        <div>{`Calc: ${calc}`}</div>
        <input autoFocus ref={inputRef} onBlur={handleBlur} onChange={handleInput} type="text" value={input} />
        </div>
      <div class="buttons" onClick={handleClick}>
       <button value="+">+</button>
       <button value="-">-</button>
       <button value="*">×</button>
       <button value="/">÷</button>
       <button value="0">0</button>
       <button value="1">1</button>
       <button value="2" >2</button>
       <button value="3">3</button>
       <button value="4">4</button>
       <button value="5">5</button>
       <button value="6">6</button>
       <button value="7">7</button>
       <button value="8">8</button>
       <button value="9">9</button>
       <button value="clear">C</button>
       <button value="Del">Del</button>
       <button value="%">%</button>
       <button value="^">y^</button>
       <button value="=">=</button>
      </div>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
.container { display: flex; width: 200px; height: 200px; }

.buttons {
  padding: 10px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 2px;
}

button {
  background: rgba(0, 0, 0, 0.5);
  border: 1px solid #111;
  padding: 10px;
  color: #EEE;
  border-radius: 5px;
  font-size: 12px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Metode alternatif yang mengurangi jumlah status dan tidak harus menggunakan useRef karena sekarang tidak ada input.

const { useRef, useEffect, useState } = React;

function Example() {

  const [ calc, setCalc ] = useState('');
  const [ result, setResult ] = useState('');
  
  // When we click a button, either update the `calc` state,
  // or if we click "=", update the `result` state
  function handleClick(e) {
    const { nodeName, value } = e.target;
    if (nodeName === 'BUTTON') {
      switch(value) {
        case '=': {
          setResult(eval(calc));
          break;
        }
        case 'clear': {
          setCalc('');
          break;
        }
        default: {
          setCalc(prev => prev + value);
          break;
        }
      }
    }
  }

  // When the result is updated, clear the `calc` state
  useEffect(() => setCalc(''), [result]);

  return (
    <div class="container">
      <div class="results">
        <div>{`Result: ${result}`}</div>
        <br />
        <div>{`Calc: ${calc}`}</div>
        </div>
      <div class="buttons" onClick={handleClick}>
       <button value="+">+</button>
       <button value="-">-</button>
       <button value="*">×</button>
       <button value="/">÷</button>
       <button value="0">0</button>
       <button value="1">1</button>
       <button value="2" >2</button>
       <button value="3">3</button>
       <button value="4">4</button>
       <button value="5">5</button>
       <button value="6">6</button>
       <button value="7">7</button>
       <button value="8">8</button>
       <button value="9">9</button>
       <button value="clear">C</button>
       <button value="Del">Del</button>
       <button value="%">%</button>
       <button value="^">y^</button>
       <button value="=">=</button>
      </div>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
.container { display: flex; }

.results { width: 40px; }

.buttons {
  margin-left: 6em;
  padding: 10px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-gap: 2px;
}

button {
  background: rgba(0, 0, 0, 0.5);
  border: 1px solid #111;
  padding: 10px;
  color: #EEE;
  border-radius: 5px;
  font-size: 12px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
1
Andy 22 September 2021, 15:30

Katakanlah Anda ingin melacak status tertunda

Untuk menggunakan useState, pertama-tama Anda harus mengimpornya

import { useState } from "react";

Kemudian,

const [ isPending , setIsPending ] = useState(false);

Nilai yang Anda berikan ke fungsi useState(initialValue) akan menjadi nilai awal status. Anda dapat meneruskan nilai apa pun seperti array string atau object ke fungsi useState()

Untuk mengatur/mengubah nilai status yang Anda nyatakan

setIsPending(true);

Nilai status Anda dipegang oleh variabel isPending

1
VH Abeyvickrama 22 September 2021, 10:43
function App() {
const [buttonText, setButtonText] = useState("InitialValue");
const [sum1, setSum1] = useState(0);
const [sum2, setSum2] = useState(0);

  const handleClick = (props) =>{
    setButtonText(props.target.value)
    let inputText = document.getElementById('result').value;
    console.log(inputText + buttonText);
    
      let  total = inputText + buttonText;
        if (total.charAt(0) === "0") {
          
        } else {
          document.getElementById("result").value = total;
        }
        if (props.target.value === "clear") {
          document.getElementById("result").value = "";
        }
        if (props.target.value === "+") {
          setSum1(parseFloat(document.getElementById("result").value));
          // alert(sum1);
          document.getElementById("result").value = "";
          
        }
        if (props.target.value === "=") {
          
            alert(sum1);
          setSum2(parseFloat(document.getElementById("result").value))
            
            document.getElementById("result").innerText = sum1+sum2;
          }
        return total;
  }
    return(
///my code
)

Silakan coba ini sekarang.

0
Dawood Ahmad 22 September 2021, 10:51