我尝试为我的Draft.js制作我的第一个装饰器。到目前为止基于documentation我做了:
名为LinkDecorator.js
的文件:
import React from 'react';
import Utils from './Utils';
const Link= (props) => {
console.log(props);
return (
<a href="http://google.com">GOOGLE</a>
);
}
const matchFunction = (contentBlock, callback, contentState) => {
/**
* Regex found in: https://stackoverflow.com/a/17773849/4706711
*/
const regex=/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/
Utils.regexMatch(regex,contentBlock,contentState);
}
export default {
'strategy': matchFunction,
'component': Link
};
使用以下文件提供名为Utils.js
的实用程序:
export default {
/**
* A utility function that is used on Composite Decorators for handling
* regex - based text maniluplation.
* @param {Regex} regex The regular expression to handle
* @param {Object} contentBlock The content block that needs to get manipulated
* @param {Function} callback A callback function that gets called when the regex matches
*/
'regexMatch': (regex, contentBlock, callback)=>{
const text = contentBlock.getText();
let matchArr = regex.exec(text);
let start;
console.log("Block Content", text);
while (matchArr !== null) {
start = matchArr.index;
callback(start, start + matchArr[0].length);
matchArr = regex.exec(text);
}
},
}
我尝试使用以下编辑器:
import React, { Component } from 'react';
import { EditorState, CompositeDecorator } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import Link from './LinkDecorator';
class MyEditor extends Component {
constructor(props){
super(props);
const compositeDecorator = new CompositeDecorator([Link]);
this.state = {
compositeDecorator,
editorState: EditorState.createEmpty(compositeDecorator),
};
}
onEditorStateChange: Function = (editorState) => {
this.setState({editorState,});
};
render() {
const { editorState } = this.state;
return (
<Editor
editorState={editorState}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
/>
);
}
}
export default MyEditor;
我还在https://github.com/pc-magas/react-draft-wysiwyg-scenario/tree/text_manipulation上提供了这些示例。正如您所见,我尝试当用户提供类型链接到编辑器时,我尝试为Google插入链接。但由于某种原因,它只是将用户提供的链接放在没有任何明显变化的情况下。
你知道为什么吗?我也想知道如何解决这个问题。
超过./LinkDecorator.js
我将matchFunction
更改为:
const matchFunction = (contentBlock, callback, contentState) => {
/**
* Regex found in: https://stackoverflow.com/a/17773849/4706711
*/
const regex=/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/
Utils.regexMatch(regex,contentBlock,callback);
}
仍未对粘贴的链接进行任何更改。