最佳答案
看了源码,找到了方法。使用 blockRenderMap
,您可以像这样添加一些自定义 block 类型:
const blockRenderMap: Record<string, DraftBlockRenderConfig> = {
'header-one-right': {
element: 'h1',
wrapper: <StyleHOC style={{ ...blockStylesMap['header-one'], display: 'flex', justifyContent: 'flex-end' }} />,
},
'header-two-right': {
element: 'h2',
wrapper: <StyleHOC style={{ ...blockStylesMap['header-two'], display: 'flex', justifyContent: 'flex-end' }} />,
},
'header-three-right': {
element: 'h3',
wrapper: <StyleHOC style={{ ...blockStylesMap['header-three'], display: 'flex', justifyContent: 'flex-end' }} />,
},
'unstyled-right': {
element: 'div',
wrapper: <StyleHOC style={{ ...blockStylesMap['unstyled'], display: 'flex', justifyContent: 'flex-end' }} />,
},
};
我使用 flex
来避免浪费时间寻找覆盖内部样式的方法 .public-DraftStyleDefault-ltr
。
StyleHOC 非常简单:
const StyleHOC: React.FC<Props> = ({ style, children }) => {
const childrenWithStyle = React.Children.map(children, (child) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, { style });
}
return child;
});
return <>{childrenWithStyle}</>;
};
然后您可以使用 RichUtils.toggleBlockType(editorState, blockType)
切换 blockType
。
关于javascript - 如何在 Draft.js 中对齐文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39262994/