如何创建一个新的 DraftInlineStyle?

How to create a new DraftInlineStyle?

我尝试用 Modifier.insertText 创建一个新状态,第三个参数应该是 draftInlineStyle

let ncs = Modifier.insertText(contentStates, selections, superscriptVar, ["BOLD"]);

这确实加粗了,但是当我稍后尝试更改样式时,它并没有改变。我发现这是因为 draftInlineStyle 应该是一个构造函数。那么,如果我应该传递 draftInlineStyle 构造函数,我该如何创建 draftInlineStyle 构造函数呢?或者还有其他方法吗?

您应该使用 Immutable.js 中的 OrderedSet.of

let ncs = Modifier.insertText(
  contentStates,
  selections,
  superscriptVar,
  OrderedSet.of('BOLD')
);

如果要应用多种样式,请将它们作为参数传递:OrderedSet.of('BOLD', 'ITALIC')

查看下面隐藏代码段中的简化演示:

const {Editor, RichUtils, Modifier, SelectionState, EditorState} = Draft;
const { OrderedSet } = Immutable;

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty()
    };
  }
  
  insertTextHandler = (nameOfCustomStyle) => {
    const currentSelection = this.state.editorState.getSelection();
    const currentContent = this.state.editorState.getCurrentContent();
    
    if (!currentSelection.isCollapsed()) return;

   const newContentState = Modifier.insertText(currentContent, currentSelection, 'INSERTED TEXT', OrderedSet.of('BOLD'));
  
    const newEditorState = EditorState.push(
      this.state.editorState,
      newContentState,
      'change-inline-style'
    );
  
   this._handleChange(newEditorState)
  }
  
  toggleBoldStyle = () => {
    this._handleChange(
      RichUtils.toggleInlineStyle(
        this.state.editorState,
        'BOLD'
      )
    );
  }
  
  _handleChange = (editorState) => {
    this.setState({ editorState });
  }
  
  render() {
    return (
      <div>
        <div className="container-root">
          <Editor
            placeholder="Type away :)"
            editorState={this.state.editorState}
            onChange={this._handleChange}
          />
        </div>
        <button onClick={() => this.insertTextHandler()}>
          INSERT TEXT
        </button>
        <button onClick={() => this.toggleBoldStyle()}>
          TOGGLE BOLD STYLE FOR SELECTED TEXT
        </button>
      </div>
    );
  }
}

ReactDOM.render(<Container />, document.getElementById('react-root'))
body {
  font-family: Helvetica, sans-serif;
}

.public-DraftEditor-content {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/draft-js/0.7.0/Draft.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/draft-js/0.10.0/Draft.js"></script>
<div id="react-root"></div>