首页 > 解决方案 > 如何在 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 中我有一个重置按钮。我希望当单击此重置按钮时,必须显示所有项目的原始内容。

例如,如果将“一整天都在下雨”改为“没有下雨”,当按下复位按钮时,它又会变回“一整天都在下雨”。

任何帮助将不胜感激。非常感谢您。

标签: javascripthtmlreactjs

解决方案


这样做的一种方法是将初始状态保存为默认状态,当单击重置按钮时,只需将当前状态更改为默认状态,即初始状态。

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>

推荐阅读