javascript - 如何在 React 中重置 contenteditable 元素?
问题描述
我正在渲染一组项目,其中每个项目都有一个contenteditable
字段。
应用程序.js
import { useState } from "react";
import Item from "./Item";
import "./styles.css";
export default function App() {
const [items, setItems] = useState([
{ id: 1, text: "It is raining all day long." },
{ id: 2, text: "The flower has a nice fragrance." },
{ id: 3, text: "The charging is complete." },
{ id: 4, text: "The room needs to be sweeped." }
]);
return (
<div className="App">
{items.map((item) => (
<Item key={item.id} item={item} />
))}
<button>Reset</button>
</div>
);
}
项目.js
const Item = ({ item }) => {
return (
<div>
<p contentEditable="true">{item.text}</p>
</div>
);
};
export default Item;
如您所见,在 App.js 中我有一个重置按钮。我希望当单击此重置按钮时,必须显示所有项目的原始内容。
例如,如果将“一整天都在下雨”改为“没有下雨”,当按下复位按钮时,它又会变回“一整天都在下雨”。
任何帮助将不胜感激。非常感谢您。
解决方案
这样做的一种方法是将初始状态保存为默认状态,当单击重置按钮时,只需将当前状态更改为默认状态,即初始状态。
const initialState = [
{ id: 1, text: "It is raining all day long." },
{ id: 2, text: "The flower has a nice fragrance." },
{ id: 3, text: "The charging is complete." },
{ id: 4, text: "The room needs to be sweeped." }
]
const [items, setItems] = useState(initialState);
用于复位按钮;
const onPress = () => {
setItems(initialState);
}
<button onClick={onPress}>Reset</button>
推荐阅读
- java - 将 SQL 或 UTIL DATE 转换为预期格式“dd-MMM-yyyy”,但不是字符串值
- c# - 如何检查您的表单是否已经打开并关闭它
- inheritance - 覆盖并更改函数的中间部分 Odoo
- python-3.x - arcpy python3中Origin Destination Matrix Analyst的输出问题
- javascript - 决定 State Monad 中的状态和内容
- excel - 嵌套If条件VBA
- reactjs - 来自数据的 CircleMarker 多类名
- java - 只有 1 个 onClickListener 适用于谷歌地图活动中的标记
- java - 从java中的子文档获取父文档值
- android - 如何使用 MotionLayout 调整 TextView 的大小