Taro(React)使用富文本编辑器Editor

在写项目的过程中很容易涉及到让使用者,输入一些介绍或者文本等相关功能, 前端在拿到这些文本时是需要直接渲染的,如果不使用富文本编辑器,这个时候得到的文章是没有格式的,这对于使用者来说体验非常的不好,这个时候就需要使用富文本编辑器,获取到带有标签的文本。

我在使用Taro写小程序的时候,有让用户编辑自我介绍的功能,这个时候就需要使用到富文本获取到带有标签的文本。

Editor | Taro 文档

代码

这个代码实现了,回显功能

javascript 复制代码
import { View, Editor } from "@tarojs/components";

export default function Index() {
  const [value, setValue] = useState<any>("<p>天下大定</p>");

  let editorCtx;

  const editorReady = (value: any) => {
    Taro.createSelectorQuery()
      .select("#editor")
      .context((res) => {
        editorCtx = res.context;
        // 在编辑器准备就绪时设置初始内容
        editorCtx &&
          editorCtx.setContents({
            html: value,
          });
        editorCtx && editorCtx.blur(); // 移除焦点
      })
      .exec();
  };

  // 撤销,回到上一步
  const undo = () => {
    if (editorCtx) {
      editorCtx.undo();
    }
  };

  // 清空内容
  const clear = () => {
    if (editorCtx) {
      editorCtx.clear();
    }
  };

  useEffect(() => {
    // 设置编辑器默认值
    setValue("<p>这里是回显内容</p>");
  }, []);

  // 保存内容
  const handStorage = () => {
    console.log(value);
    // 发起接口进行请求

  };

  return (
    <View className="Readme">
      {/* 富文本编辑器 */}
      <View className="padding-20 main_editor">
        <View className="padding-20 editor_father">
          <Editor
            id="editor"
            className="editor"
            onInput={(e) => setValue(e.detail.html)}
            placeholder={"你的自述..."}
            onReady={() => editorReady(value)}
          ></Editor>
        </View>

        <View className="button">
          <Button type="primary" block onClick={clear}>
            删除
          </Button>
          <Button type="primary" block onClick={undo}>
            撤销
          </Button>
          <Button
            color="#ff8e16"
            block
            type="primary"
            onClick={() => handStorage()}
          >
            保存
          </Button>
        </View>
      </View>
    </View>
  );
}

还有更多的功能,大家可以自行查看。

EditorContext | Taro 文档

相关推荐
别叫我->学废了->lol在线等21 小时前
演示 hasattr 和 ** 解包操作符
开发语言·前端·python
霍夫曼21 小时前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
DARLING Zero two♡21 小时前
浏览器里跑 AI 语音转写?Whisper Web + cpolar让本地服务跑遍全网
前端·人工智能·whisper
Lovely Ruby1 天前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·学习·golang
深红1 天前
玩转小程序AR-实战篇
前端·微信小程序·webvr
银空飞羽1 天前
让Trae SOLO全自主学习开发近期爆出的React RCE漏洞靶场并自主利用验证(CVE-2025-55182)
前端·人工智能·安全
钮钴禄·爱因斯晨1 天前
DevUI 组件生态与 MateChat 智能应用:企业级前端智能化实战
前端
不会写DN1 天前
存储管理在开发中有哪些应用?
前端·后端
清风细雨_林木木1 天前
Obsidian 笔试环境配置与使用指南
前端