使用html-to-draftjs插入带data属性的a标签时自定义属性丢失如何解决
根因说明
html-to-draftjs默认仅解析a标签的href、target等标准属性,自定义data-*属性不会被默认提取存储到Draft.js的Entity实体中,最终渲染时没有对应属性数据源就会丢失。
解决步骤
- 自定义html-to-draftjs的a标签转换规则,提取自定义属性存入Entity
import htmlToDraft from 'html-to-draftjs'; // 自定义a标签解析逻辑 const customAConverter = (nodeName, node) => { if (nodeName === 'a' && node.getAttribute('href')) { return { type: 'LINK', mutability: 'MUTABLE', data: { url: node.getAttribute('href'), target: node.getAttribute('target') || '_self', // 提取自定义data-x属性存入Entity数据 dataX: node.getAttribute('data-x') } }; } return null; }; // 组装自定义解析配置 const customParseConfig = { customChunkRenderer: (nodeName, node) => customAConverter(nodeName, node) };
- 调整原有业务代码,传入自定义配置调用htmlToDraft
const readMoreLink = `<a data-x='test' href='testlink' target='_blank'>testlinnk</a>`; // 调用时传入自定义解析配置 const draftParseResult = htmlToDraft(readMoreLink, customParseConfig); const newContent = Modifier.replaceWithFragment( editorState.getCurrentContent(), editorState.getSelection(), BlockMapBuilder.createFromArray(draftParseResult.contentBlocks) ); const newState = EditorState.push( editorState, newContent, "insert-fragment" );
- 自定义Draft.js链接渲染组件,读取Entity中的自定义属性渲染
需要给Draft.js编辑器配置装饰器,使用自定义链接组件渲染LINK类型的Entity:
import { Editor, CompositeDecorator, EditorState } from 'draft-js'; // 自定义链接渲染组件 const CustomLink = (props) => { const entityData = props.contentState.getEntity(props.entityKey).getData(); return ( <a href={entityData.url} target={entityData.target} data-x={entityData.dataX} > {props.children} </a> ); }; // 配置LINK类型Entity的渲染规则 const decorator = new CompositeDecorator([ { strategy: (contentBlock, callback, contentState) => { contentBlock.findEntityRanges( (character) => { const entityKey = character.getEntity(); return entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK'; }, callback ); }, component: CustomLink } ]); // 初始化EditorState时传入装饰器即可生效 const [editorState, setEditorState] = useState(() => EditorState.createEmpty(decorator));
如果需要保留更多自定义属性,只需在customAConverter的data字段中增加对应属性提取逻辑,再在自定义链接组件中对应渲染即可。
内容的提问来源于stack exchange,提问作者hichem chouaibi
相关产品推荐
相关产品推荐

