1

我正在尝试制作所见即所得的编辑器,可以对选定的文本进行注释。

首先,我使用了 Draft.js。但是,它不适合使用 key 来指向带注释的文本,因为 Draft.js 的实体键是在重复选择时启动的。

所以,我在搜索与这些东西相关的其他库时找到了 slatejs。

slatejs 有“setKeyGenerator”实用程序。但是,我找不到有关 slatejs 的“setKeyGenerator”的任何信息。该实用程序只是设置功能,如下所示。

function setKeyGenerator(func) {
  generate = func;
}

而且我不知道如何使用此功能生成密钥。

那么,任何人都知道如何使用此功能或对注释选定文本有任何想法吗?

4

2 回答 2

2

如果您尝试生成一个键来引用元素(块),您可以执行以下操作:

// A key to reference to block by (you should make it more unique than `Math.random()`)
var uniqueKey = Math.random();

// Insert a block with a unique key
var newState = this.state
    .transform()
    .insertBlock({
        type: 'some-block-type',
        data: {
            uniqueKey: uniqueKey
        },
    })
    .apply();

// Get the block's unique Slate key (used internally)
var blockKey;
var { document } = self.state;
document.nodes.some(function(node) {
    if (node.data.get('uniqueKey') == uniqueKey) {
        blockKey = node.key;
    }
});

// Update data on the block, using it's key to find it.
newState = newState
    .transform()
    .setNodeByKey(blockKey, {
        data: {
            // Define any data parameters you want attached to the block.
            someNewKey: 'some new value!'
        },
    })
    .apply();

这将允许您在插入块上设置唯一键,然后获取块的实际 SlateJkey并用它更新块。

于 2017-07-21T01:52:32.663 回答
0

Slate 提供了一个KeyUtils.setGenerator(myKeygenFunction)传递我们自己的密钥生成器。这使我们有机会在 Editor 实例中创建真正唯一的键。

在导入此组件的父级中,idFromParentIteration为每个PlainText组件实例传递不同的道具,您应该会很好。像这样:

['first-editor', 'second-editor'].map((name, idx) => <PlainText idFromParentIteration={name + idx} />)

这是一个带有自定义密钥生成器的完整示例。

import React from "react";
import Plain from "slate-plain-serializer";
import { KeyUtils } from 'slate';
import { Editor } from "slate-react";

const initialValue = Plain.deserialize(
  "This is editable plain text, just like a <textarea>!"
);

class PlainText extends React.Component {
  constructor(props) {
    super(props);
    let key = 0;
    const keygen = () => {
      key += 1;
      return props.idFromParentIteration + key; // custom keys
    };
    KeyUtils.setGenerator(keygen);
  }
  render() {
    return (
      <Editor
        placeholder="Enter some plain text..."
        defaultValue={initialValue}
      />
    );
  }
}

export default PlainText;
于 2019-01-11T08:08:51.157 回答