【问题标题】:ReactJS and DraftJS, how to change font size on the fly?ReactJS 和 DraftJS,如何动态更改字体大小?
【发布时间】:2019-07-26 04:51:08
【问题描述】:

我有以下代码可以完美地用于斜体、粗体和下划线:

    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'));
  };

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

【问题讨论】:

    标签: reactjs wysiwyg draftjs


    【解决方案1】:

    首先,你需要创建一个自定义的内联样式

    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

    【讨论】:

      【解决方案2】:

      我认为这应该适用于您的情况

      toggleFontSize = fontSize => {
         const { editorState } = this.state;
         RichUtils.toggleBlockType( editorState, fontSize  );
      }
      
      <button onClick={e => this.toggleFontSize('100px')}>100px</button>
      

      更多解释请查看-https://www.npmjs.com/package/draft-js-custom-styles#api

      在文档中,他们给出了一个例子

      toggleFontSize = fontSize => {
        const newEditorState = styles.fontSize.toggle(this.state.editorState, 
        fontSize);
      
        return this.updateEditorState(newEditorState);
      };
      

      【讨论】:

      猜你喜欢
      • 2021-06-06
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多