reactjs - 如何在单击按钮时更改字体大小?

标签 reactjs draftjs

这是我尝试过的:

constructor(props) {
  super(props);
  this.state = {editorState: EditorState.createEmpty()};

  this.focus = () => this.refs.editor.focus();
  this.onChange = (editorState) => this.setState({editorState});

  this.toggleFontSize = (fontSize) => this._toggleFontSize(fontSize);
}

_toggleFontSize(fontSize) {
  this.onChange(
    RichUtils.toggleBlockType(
      this.state.editorState,
      fontSize
    )
  );
}

<button onClick={e => this.toggleFontSize('100px')}>100px</button>

最佳答案

更改 fontSize 就像在 Draftjs 上管理任何其他内联样式一样有点棘手,特别是如果您对 Immutable 模型如何在 ContentState 和 EditorState 上工作知之甚少。 自定义任何内联样式的最简单方法是使用 draft-js-custom-styles模块。

以下是如何在文本选择上切换字体大小:

import createStyles from "draft-js-custom-styles";
const customStylesToManage = ["font-size", "color"];
const { styles, customStyleFn, exporter } = createStyles(customStylesToManage, "CUSTOM_")
//CUSTOM_ is going to be used as a prefix for you inline styles

现在您必须在主 Draftjs 编辑器上使用 customStyleFn 以在切换时应用样式

<Editor customStyleFn={customStyleFn} ... />

要将特定样式应用于文本选择,您只需调用样式切换

const newEditorState = styles.fontSize.toggle(editorState, "27px");

并确保更新 editorState 以应用内联样式

updateEditorState(newEditorState);

也支持其他方法,例如,您可以从文本选择中完全删除样式、添加新样式或获取当前内联样式值:

const currentFontSizeForSelectedText = styles.fontSize.current;

检查模块的Docs了解更多详细信息。

关于reactjs - 如何在单击按钮时更改字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52881874/

相关文章:

javascript - 我应该使用 useselector/useDispatch 而不是 mapStateToProps

reactjs - 如何从draftjs中检索文本

javascript - 如何在数据库中存储富文本

javascript - 检查 DraftJS 中的 contentState 是否更改或只是 editorState 的最佳性能方法

javascript - 无法找到 .jsx 和 js 文件之间的真正区别

javascript - 更改时的 setState

reactjs - 使用 TypeScript 为 React 高阶组件输入注解

javascript - 如何从 Draft.js json 渲染 React.js 内容

javascript - Draftjs 尝试删除原子 block

javascript - Draft.js 自定义内容 block 不显示