如何在draftjs编辑器中修改样式?

时间:2018-09-06 08:08:37

标签: reactjs draftjs

我正在尝试使用draftjs,并希望创建一个自定义块组件。

第一个问题是,我无法完美完成在文档(link here)中创建的示例。

当我单击名为“ bold”的按钮时,编辑器将失去焦点,并且我的文本也不会变粗。

这是我的代码:

import React, { Component } from 'react';
import { Editor, EditorState, RichUtils } from 'draft-js';
import { Paper, Button } from '@material-ui/core';

class ProductComponent extends Component {
  render() {
    const { src } = this.props;

    return (
      <div>{src}</div>
    )
  }
}

export default class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty()
    }
  }


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

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

  myBlockStyleFn = (contentBlock) => {
    const type = contentBlock.getType();
    if (type === 'product') {
      return {
        component: ProductComponent,
        editable: false,
        props: {
          src: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3307626454,3432420457&fm=27&gp=0.jpg',
        },
      }
    }
  }

  render() {
    const {editorState} = this.state;

    return (
      <Paper elevation={0}>
        <Button onClick={this.onBoldClick}>bold</Button>

        <Editor
          blockStyleFn={this.myBlockStyleFn}
          editorState={editorState}
          onChange={this.onChange}
        />
      </Paper>
    );
  }
}

0 个答案:

没有答案