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

相关推荐
emojiwoo1 小时前
【前端基础知识系列六】React 项目基本框架及常见文件夹作用总结(图文版)
前端·react.js·前端框架
张人玉2 小时前
XML 序列化与操作详解笔记
xml·前端·笔记
杨荧2 小时前
基于Python的宠物服务管理系统 Python+Django+Vue.js
大数据·前端·vue.js·爬虫·python·信息可视化
YeeWang2 小时前
🎉 Eficy 让你的 Cherry Studio 直接生成可预览的 React 页面
前端·javascript
gnip3 小时前
Jenkins部署前端项目实战方案
前端·javascript·架构
Orange3015113 小时前
《深入源码理解webpack构建流程》
前端·javascript·webpack·typescript·node.js·es6
lovepenny3 小时前
Failed to resolve entry for package "js-demo-tools". The package may have ......
前端·npm
超凌3 小时前
threejs 创建了10w条THREE.Line,销毁数据,等待了10秒
前端
车厘小团子4 小时前
🎨 前端多主题最佳实践:用 Less Map + generate-css 打造自动化主题系统
前端·架构·less
芒果1254 小时前
SVG图片通过img引入修改颜色
前端