简体   繁体   中英

How can I get the input changed value when onClick2 is pressed in onClick3?

onClick2 causes the state to receive the changed value.

However, onClick3 wants to deliver the changed state value only when onClick2 is pressed.

How can I control the changed value of the input?

When onClick3 is pressed when the input value is changed to 456 Is it possible to get the previous value of onChange?

my code...

import React, { useRef, useState } from "react";

const App = () => {
  const [value, setValue] = useState("123");

  const onChangeInput = (e) => {
    setValue(e.target.value);
  };

  const onClick2 = () => {
    console.log(value);
  };

  const onClick3 = () => {
    // how to onclick2 preve
    console.log(value);
  };

  return (
    <div>
      <input type="text" onChange={onChangeInput} value={value} />
      <button onClick={onClick2}>Button1</button>
      <button onClick={onClick3}>Button2</button>
    </div>
  );
};

export default App;

You should use 2 useState one for prevValue and one for currentValue like this-

const [value, setValue] = useState("123")
const [prevValue, setPrevValue] = useState(value)

const onChangeInput = (e) => {
    setValue(e.target.value);
}

const onClick2 = () => {
    setPrevValue(value)
}

const onClick3 = () => {
    console.log('Previous : ', prevValue)
    console.log('Current : ', value)
}

When you click on onClick2 btn it will update previous Value and when you click on onClick3 btn it will give you output as previous and updated Values.

# If your current value is 456

output: 
    Previous : 123
    Current : 456

Just add this code and you will get your answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM