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 文档

相关推荐
爱分享的程序猿-Clark15 分钟前
【前端分享】CSS实现3种翻页效果类型,附源码!
前端·css
Code哈哈笑30 分钟前
【图书管理系统】深度讲解:图书列表展示的后端实现、高内聚低耦合的应用、前端代码讲解
java·前端·数据库·spring boot·后端
无名之逆1 小时前
Hyperlane: Unleash the Power of Rust for High-Performance Web Services
java·开发语言·前端·后端·http·rust·web
数据潜水员1 小时前
`待办事项css样式
前端·css·css3
_处女座程序员的日常1 小时前
css媒体查询及css变量
前端·css·媒体
GanGuaGua3 小时前
CSS:盒子模型
开发语言·前端·css·html
进取星辰3 小时前
23、Next.js:时空传送门——React 19 全栈框架
开发语言·javascript·react.js
GalenWu9 小时前
对象转换为 JSON 字符串(或反向解析)
前端·javascript·微信小程序·json
GUIQU.9 小时前
【Vue】微前端架构与Vue(qiankun、Micro-App)
前端·vue.js·架构
zwjapple9 小时前
“ES7+ React/Redux/React-Native snippets“常用快捷前缀
javascript·react native·react.js