首页 > 解决方案 > ReactJS 和 DraftJS,如何动态更改字体大小?

问题描述

我有以下代码非常适合斜体、粗体和下划线:

    onUnderlineClick = () => {
        this.onChange(
            RichUtils.toggleInlineStyle(this.state.editorState, "UNDERLINE")
        );
    };

    onBoldClick = () => {
        this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, "BOLD"));
    };

    onItalicClick = () => {
        this.onChange(
            RichUtils.toggleInlineStyle(this.state.editorState, "ITALIC")
        );
    };

现在我想添加一个更改字体大小的按钮,我尝试过:

  onHeaderClick = () => {
       this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, '30px'));
  };

但它不起作用......如何更改所选文本的字体大小?

标签: reactjswysiwygdraftjs

解决方案


首先,您需要创建自定义内联样式

const inlineStyles = [
  { label: "B", style: "BOLD" },
  { label: "I", style: "ITALIC" },
  { label: "U", style: "UNDERLINE" },
  { label: "<strike>S</strike> ", style: "STRIKETHROUGH" },
  { label: "I am your header", style: "FONT_SIZE_30" }
];

并用它来建立一个菜单

二、需要定义自定义样式图

const customStyleMap = {
  STRIKETHROUGH: {
    textDecoration: "line-through"
  },
  FONT_SIZE_30: {
    fontSize: "30px"
  }
};

并通过它:

class MyEditor extends React.Component {
  // ...
  render() {
    return (
      <Editor
        customStyleMap={styleMap}
        editorState={this.state.editorState}
        ...
      />
    );
  }
}

查看 Codesanbox 上的完整示例https://codesandbox.io/s/font-size-inline-we2q2

DraftJS 内联样式文档https://draftjs.org/docs/advanced-topics-inline-styles


推荐阅读