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

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

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

Editor | Taro 文档

代码

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

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

相关推荐

  1. uniapp-app使用文本编辑器editor

    2024-06-07 14:40:04       31 阅读
  2. Taro(React)使用文本编辑器Editor

    2024-06-07 14:40:04       8 阅读
  3. uniapp - editor 文本使用

    2024-06-07 14:40:04       34 阅读
  4. vue-html5-editor文本编辑器抓取网络图片本地化

    2024-06-07 14:40:04       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-07 14:40:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-07 14:40:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-07 14:40:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-07 14:40:04       20 阅读

热门阅读

  1. Mybatis动态SQL

    2024-06-07 14:40:04       7 阅读
  2. Kotlin getter 和 setter

    2024-06-07 14:40:04       10 阅读
  3. # ROS 获取激光雷达数据 (Python实现)

    2024-06-07 14:40:04       8 阅读
  4. vue2 集成element 步骤

    2024-06-07 14:40:04       6 阅读
  5. 基于Spring Security添加流控

    2024-06-07 14:40:04       11 阅读