跳到主要内容

3. 栈(Stack)

3. 栈(Stack)

示例场景:实现一个简单的撤销功能,用户可以撤销最近的操作。

import React, { useState } from "react";

function UndoableInput() {
const [value, setValue] = useState("");
const [history, setHistory] = useState([]);
const [currentStep, setCurrentStep] = useState(0);

const handleChange = (e) => {
const newValue = e.target.value;
setValue(newValue);
setHistory([...history.slice(0, currentStep), newValue]);
setCurrentStep(currentStep + 1);
};

const handleUndo = () => {
if (currentStep > 0) {
setCurrentStep(currentStep - 1);
setValue(history[currentStep - 1]);
}
};

return (
<div>
<input type="text" value={value} onChange={handleChange} />
<button onClick={handleUndo} disabled={currentStep === 0}>
撤销
</button>
</div>
);
}

export default UndoableInput;