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

相关推荐
这里有鱼汤20 分钟前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
用户21411832636021 小时前
dify案例分享-免费玩转 AI 绘图!Dify 整合 Qwen-Image,文生图 图生图一步到位
前端
IT_陈寒1 小时前
Redis 性能翻倍的 7 个冷门技巧,第 5 个大多数人都不知道!
前端·人工智能·后端
mCell8 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip8 小时前
Node.js 子进程:child_process
前端·javascript
excel11 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel12 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼14 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping14 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙15 小时前
[译] Composition in CSS
前端·css