首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在slate js中为特定关键字着色

如何在slate js中为特定关键字着色
EN

Stack Overflow用户
提问于 2021-09-27 22:28:12
回答 1查看 180关注 0票数 0

试图让单词"hello“以不同的颜色显示,使用了几乎1:1的示例,但无法正常工作。

每当我输入"hello“时,文本就会在我写的时候出现两次。

我的代码:

代码语言:javascript
复制
import { Editable, Slate, withReact } from "slate-react";
import React, { useMemo, useState } from "react";
import { Text, createEditor } from "slate";

import { withHistory } from "slate-history";

const log = (x) => {
  console.log(x);
  return x;
};
const tokenize = (text) =>
  text
    .split(/(\s+)/)
    .map((x) => (x === "hello" ? { content: x, type: "keyword" } : x));

const getLength = (token) =>
  typeof token === "string"
    ? token.length
    : typeof token.content === "string"
    ? token.content.length
    : token.content.reduce((l, t) => l + getLength(t), 0);

const Leaf = ({ attributes, children, leaf }) => (
  <span
    style={{ color: log(leaf).keyword ? "green" : "black" }}
    {...attributes}
  >
    {log(children)}
  </span>
);

const CodeEditor = () => {
  const [value, setValue] = useState([
    {
      type: "paragraph",
      children: [
        {
          text: "",
        },
      ],
    },
  ]);
  const editor = useMemo(() => withHistory(withReact(createEditor())), []);
  return (
    <Slate editor={editor} value={value} onChange={(value) => setValue(value)}>
      <Editable
        decorate={decorate}
        renderLeaf={(props) => <Leaf {...props} />}
        placeholder="Write some code..."
      />
    </Slate>
  );
};

const decorate = ([node, path]) => {
  if (!Text.isText(node)) {
    return [];
  }
  const ranges = [];
  const tokens = tokenize(node.text);
  let start = 0;
  for (const token of tokens) {
    const end = start + getLength(token);
    if (typeof token !== "string") {
      ranges.push({
        [token.type]: true,
        anchor: { path, offset: start },
        focus: { path, offset: end },
      });
    }
    start = end;
  }
  return ranges;
};

export default CodeEditor;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-29 12:36:43

代码没有问题,这是https://github.com/ianstormtaylor/slate/pull/4556修复的库中的一个错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69353903

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档