gpt4 book ai didi

draftjs - 如何创建一个新的 DraftInlineStyle?

转载 作者:行者123 更新时间:2023-12-04 12:46:06 27 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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>

关于draftjs - 如何创建一个新的 DraftInlineStyle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com