我想知道如何在Draft.js中对齐文本,如下图所示。
我已经搜索了几天,但我还没有找到解决方案。
在阅读了源代码后,我找到了一种方法。使用blockRenderMap
,您可以添加一些自定义块类型,如下所示:
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}</>;
};
然后你可以切换blockType
using RichUtils.toggleBlockType(editorState, blockType)
。
The Editor component has a div with the class .public-DraftStyleDefault-ltr
. This controls the text alignment of each paragraph that you write. As you create more paragraphs, more of these divs are created to contain the text. The text is wrapped in a span element and .public-DraftStyleDefault-ltr
has a default alignment of text-align: left
.
I created some css classes for text-align: left
, text-align: center
, text-align: right
and text-align: justify
and added this basic for loop to my component for creating text alignment buttons.
const textBlock = document.querySelectorAll(".public-DraftStyleDefault-ltr");
for (let i = 0; i < textBlock.length; i++) {
textBlock[i].classList.toggle(this.props.style);
}
this.props.style is the name of the css class that determines the text-alignment I wanted.
It is a pretty basic fix since this way when you click align right say, the whole document is aligned right. I am planning to work on this so only the selected text is aligned so should be able to update this answer soon. Hope it helps in some way
我试着做几乎一样的东西。但我的麻烦在于 text-align 属性,它被正确设置为块跨度,但.public-DraftStyleDefault-ltr
没有对其做出反应。
所以,我做了下一个决定,得到第一个 div 孩子,并复制它的参数:
const paragraphs: any = document.querySelectorAll(".public-DraftStyleDefault-ltr");
for (let i = 0; i < paragraphs.length; i++) {
const paragraph = paragraphs.item(i);
if (paragraph) {
const firstItem = paragraph.querySelectorAll('*').item(0);
// Apply to the parent the first child style
paragraph.style.textAlign = firstItem.style.textAlign;
}
}