我试图用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>