reactjs - 如何在 slate js 中为特定关键字着色
问题描述
试图让单词“hello”以不同的颜色出现,使用示例中的示例几乎 1:1,但无法使其正常工作。
每当我输入“你好”时,文本开始出现两次。
我的代码:
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;
解决方案
推荐阅读
- pandas - 如何使用 Python 从组合的出现中形成计数矩阵?
- macos - Mac上的docker,在任何目录上安装卷失败“安装被拒绝:EOF”
- python - Python 中的快速数据集增强 - 深度学习
- javascript - 如何使用 jspdf-Autotable 在表格中添加自定义最后一行
- android - 在没有操作栏的情况下显示活动标题的好方法是什么?
- reactjs - 使用 Redux 和 React Hooks 设置状态的最佳方式
- r - 如何在 R 中对数据框中的值求和?
- javascript - 如果输入文件类型有值(Bootstrap4),则在关闭模式之前显示确认消息
- javascript - 动态地将 css 赋予数组中的元素
- r - 在需要列规范的函数上使用 purrr::map