Draft.js-CompositeDecorator:有没有一种方法可以将信息从策略传递到组件



假设我的策略计算一些编号标签。如何将其传递给decorator组件(例如通过props(。

我知道CompositeDecorator中有一个props属性,但我如何从策略函数访问它?

我对DraftJs有点陌生,但基于我的理解:

应该使用策略来确定需要修饰的文本的范围。装饰的呈现(可能包括计算标签应该是什么(应该在组件本身而不是策略中处理。

您应该能够通过组件中的props对象访问ContentState,并据此计算标签。组件的构造函数可能是执行计算标签的逻辑的好地方。这也意味着,您可能必须为装饰器组件使用类定义,而不是像draftjs网站上的示例所示的纯函数。

您还可以通过使用regex从文本中读取值来规避此问题。下面的例子是用@draft js插件完成的:

// How the section is detected.
const strategy = (contentBlock, callback) => {
const text = contentBlock.getText();
const start = text.indexOf('<_mytag ');
const endTag = '/>';
const end = text.indexOf(endTag);
if (start !== -1 && end !== -1) {
callback(start, end + endTag.length);
}
};
// What is rendered for the detected section.
const component = ({ decoratedText }) => {
if (decoratedText) {
const label = decoratedText.match(/label="([a-zA-Z0-9/s]*?)"/);
if (
label &&
typeof label[1] === 'string'
) {
return <div>{label[1]}</div>;
}
return null;
}
};
export const MyTagPlugin = {
decorators: [
{
strategy,
component,
},
],
};

最新更新