13

我想知道如何在Draft.js中对齐文本,如下图所示。

文本对齐

我已经搜索了几天,但我还没有找到解决方案。

4

3 回答 3

1

在阅读了源代码后,我找到了一种方法。使用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}</>;
};

然后你可以切换blockTypeusing RichUtils.toggleBlockType(editorState, blockType)

于 2021-03-20T16:33:59.483 回答
0

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

于 2019-09-10T14:52:30.603 回答
0

我试着做几乎一样的东西。但我的麻烦在于 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;
    }
}
于 2019-10-18T09:27:23.610 回答