如何创建一个新的 DraftInlineStyle?

ill*_*ter 3 draftjs

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

let ncs = Modifier.insertText(contentStates, selections, superscriptVar, ["BOLD"]);
Run Code Online (Sandbox Code Playgroud)

这确实给了粗体,但是当我稍后尝试更改样式时,它不会改变。我发现这是因为 DraftInlineStyle 应该是一个构造函数。那么,如果我应该传递一个 DraftInlineStyle 构造函数,我该如何创建一个 DraftInlineStyle 构造函数呢?或者有没有其他方法可以做到这一点?

Mik*_*kov 5

你应该使用OrderedSet.of来自 Immutable.js。

let ncs = Modifier.insertText(
  contentStates,
  selections,
  superscriptVar,
  OrderedSet.of('BOLD')
);
Run Code Online (Sandbox Code Playgroud)

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

检查下面隐藏片段中的简化演示:

let ncs = Modifier.insertText(
  contentStates,
  selections,
  superscriptVar,
  OrderedSet.of('BOLD')
);
Run Code Online (Sandbox Code Playgroud)
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'))
Run Code Online (Sandbox Code Playgroud)
body {
  font-family: Helvetica, sans-serif;
}

.public-DraftEditor-content {
  border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)