javascript - 使用 react-hooks 在文本区域中显示本地存储值
问题描述
我正在尝试在 React 中做一个笔记应用程序。
我设法将状态保存在本地存储中。
我的目标是textarea
在渲染和刷新中显示本地存储“注释”。到目前为止,在刷新时,占位符显示在渲染上。
我想要:
- 如果本地存储中没有笔记显示占位符
- 如果注释存在于本地,则将它们显示在文本区域中。
继承人的代码:
const [notes, setNotes] = useState("")
useEffect(() => {
const notes = localStorage.getItem("notes")
if (notes) {
setNotes(JSON.parse(notes))
}
})
const handleChange = e => {
setNotes(e.target.value)
localStorage.setItem("notes", JSON.stringify(e.target.value))
}
return (
<form>
<label for="pad">
<span>Add your notes</span>
<textarea
rows="10"
placeholder="Add notes here "
name="pad"
onChange={handleChange}
></textarea>
</label>
</form>
)
解决方案
value
使用带有notes
变量的文本区域。对于此示例,您不需要 useEffect。即使你想使用它,也请添加你的依赖数组。
export default function App() {
const localNotes = localStorage.getItem("notes");
const [notes, setNotes] = useState(localNotes);
const handleChange = e => {
localStorage.setItem("notes", e.target.value);
setNotes(e.target.value);
};
return (
<form>
<label for="pad">
<span>Add your notes</span>
<textarea
rows="10"
placeholder="Add notes here "
name="pad"
value={notes}
onChange={handleChange}
/>
</label>
</form>
);
}
推荐阅读
- jquery - 使用 jQuery 从带有连字符的列名的谷歌表中读取数据
- java - 可分页实例化在 WebMvcTest 中成功,在运行服务器上失败
- scala - 从类型参数中获取子类型参数
- ruby-on-rails - 查询第一条记录时枚举集合数组的索引不起作用,这是为什么呢?
- c# - C# Unity:在附加到 GameObject 的脚本中获取公共类
- prolog - 如何编写计算平均工资的 prolog 规则?
- c# - 如何通过子控件事件更改父控件的内容?
- excel - 在 Excel VBA 中使用“Get #COMfile, , record”读取串行端口似乎有无限超时?
- linux - 为一个目录中的所有文件生成MD5sum,并在另一个目录中获取它们的匹配项
- python - Jupyter实验室:是否可以仅在单独的视图中显示输出