【发布时间】:2020-05-12 01:12:16
【问题描述】:
我正在使用 Draftjs 和 Draft-js-plugins-editor,我正在使用两个插件:draft-js-mathjax-plugin 和 draft-js-mention-plugin
当用户使用“@”提及元素时,我想稍后用值替换所有提及。例如,“你有@A”将被“你有 300”替换。我找到并使用了Draft-js building search and replace functionality,它有很好的文档和解释。 我改变了一点函数以使它们更全球化:
function findWithRegex (regex, contentBlock, callback) {
const text = contentBlock.getText();
let matchArr, start, end;
while ((matchArr = regex.exec(text)) !== null) {
start = matchArr.index;
end = start + matchArr[0].length;
callback(start, end);
}
}
function Replace (editorState,search,replace) {
const regex = new RegExp(search, 'g');
const selectionsToReplace = [];
const blockMap = editorState.getCurrentContent().getBlockMap();
blockMap.forEach((contentBlock,i) => (
findWithRegex(regex, contentBlock, (start, end) => {
const blockKey = contentBlock.getKey();
const blockSelection = SelectionState
.createEmpty(blockKey)
.merge({
anchorOffset: start,
focusOffset: end,
});
selectionsToReplace.push(blockSelection)
})
));
let contentState = editorState.getCurrentContent();
selectionsToReplace.forEach((selectionState,i) => {
contentState = Modifier.replaceText(
contentState,
selectionState,
replace
)
});
return EditorState.push(
editorState,
contentState,
);
}
单独运行效果很好,但是当我使用 mathjax-plugin 进行数学表达式,然后使用 Replace 函数时,所有数学内容都消失了......
我知道在replaceText 函数的定义中我们可以插入inlineStyle,但我没有找到任何“提取”样式的方法。
我尝试使用getEntityAt、findStyleRanges、findEntityRanges 和其他功能,但我无法让它们做我想做的事......
这是我的反应组件:
import React, { Component } from 'react';
import {EditorState, SelectionState, Modifier, convertFromRaw, convertToRaw} from 'draft-js';
import Editor from 'draft-js-plugins-editor';
import createMathjaxPlugin from 'draft-js-mathjax-plugin';
import createMentionPlugin, { defaultSuggestionsFilter } from 'draft-js-mention-plugin';
export default class EditorRplace extends Component {
constructor(props) {
super(props);
this.mentionPlugin = createMentionPlugin({
entityMutability: 'IMMUTABLE',
mentionPrefix: '@'
});
//We recover the data from the props
let JSONContentState = JSON.parse(this.props.instruction);
let inputs = this.props.inputs;
let values = this.props.values;
this.state = {
editorState: EditorState.createWithContent(convertFromRaw(JSONContentState)),
plugins:[this.mentionPlugin,createMathjaxPlugin({setReadOnly:this.props.isReadOnly})],
trigger:this.props.trigger,
inputs:inputs,
values:values,
};
}
componentDidMount() {
this.setState({
editorState:onReplace(this.state.editorState,'A','B')
})
}
onChange = (editorState) => {
this.setState({
editorState:editorState,
})
};
render() {
return (
<div>
<Editor
readOnly={true}
editorState={this.state.editorState}
plugins={this.state.plugins}
onChange={this.onChange}
/>
</div>
);
}
}
如果我没有使用替换功能,所有内容都会按预期显示,使用正确样式的提及和数学表达式。
【问题讨论】:
标签: javascript reactjs draftjs draft-js-plugins