我正在嘗試使用 React 和 localStorage 做一個可保存的筆記。每當點擊' Save ' 時,它應該將textarea 中的值保存到localStorage,并且每當點擊' Clear ' 時,它應該清除 textarea和localStorage 中的資料。
import { useState } from "react";
import "./App.css";
function App() {
const storage = window.localStorage;
const [text, setText] = useState('');
const data = storage.getItem('text');
return (
<div className="App">
<div className="box">
<div className="field">
<div className="control">
<textarea
className="textarea is-large"
placeholder="Notes..."
value={data}
onChange={(e) => setText(e.target.value)} />
</div>
</div>
<button
className="button is-large is-primary is-active"
onClick={() => storage.setItem('text', text)}>Save</button>
<button
className="button is-large"
onClick={() => {storage.removeItem('text'); setText('')}}>Clear</button>
</div>
</div>
);
}
export default App;
它按預期作業,除了當我單擊'save' 時,我無法在 textarea 中鍵入或洗掉任何內容。此外,當我單擊“清除”時,它僅在我重新加載頁面后才清除該框。
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
首先,您應該使用 state 變數設定 textarea 的值text,否則一旦單擊保存就無法再編輯它。這是因為本地存盤上的值在您鍵入時保持不變,因此無法更新該值。
其次,您需要將狀態變數初始化text為本地存盤中的值(如果有)。否則,重繪 時它將始終為空。
應用這兩項更改的代碼如下:
function App() {
const storage = window.localStorage;
const data = storage.getItem('text');
const [text, setText] = useState(data ?? '');
return (
<div className="App">
<div className="box">
<div className="field">
<div className="control">
<textarea
className="textarea is-large"
placeholder="Notes..."
value={text}
onChange={(e) => setText(e.target.value)} />
</div>
</div>
<button
className="button is-large is-primary is-active"
onClick={() => storage.setItem('text', text)}>Save</button>
<button
className="button is-large"
onClick={() => {storage.removeItem('text'); setText('')}}>Clear</button>
</div>
</div>
);
}
export default App;
uj5u.com熱心網友回復:
在textArea元素中,您必須將“值”分配為“文本”狀態。
<textarea
className="textarea is-large"
placeholder="Notes..."
value={text} // --> here
onChange={(e) => setText(e.target.value)} />
請參閱此處:作業示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/329669.html
標籤:javascript 反应 本地存储
