gpt4 book ai didi

reactjs - 如何检查 draft js Editor 中的空格

转载 作者:行者123 更新时间:2023-12-01 22:11:57 24 4
gpt4 key购买 nike

我如何检查编辑器中是否有空格?当编辑器中有空白时,我不想提交表单。我正在使用这个功能来检测编辑器是否为空,但它不会检测编辑器是否有空格

contentState.hasText()

最佳答案

您可以使用两种方法检查编辑器内容,您可以在当前内容状态下调用这两种方法。第一 - hasText第二个getPlainText

查看下面的演示。这里我们检查三种不同的编辑条件:

  • 编辑器是空的(没有空格,没有字母,没有其他字符),

  • 是编辑器只包含空格(没有其他字符),

  • 是编辑器包含一些文本(除空格外的任何字符)

const {Editor, EditorState} = Draft;

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

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

_checkEditorContent = () => {
const content = this.state.editorState.getCurrentContent();
const isEditorEmpty = !content.hasText();
const currentPlainText = content.getPlainText()
const lengthOfEditorContent = currentPlainText.length;
const lengthOfTrimmedContent = currentPlainText.trim().length;
const isContainOnlySpaces = !isEditorEmpty && !lengthOfTrimmedContent;

console.clear();
console.log('editor empty => ', isEditorEmpty)
console.log('editor containe only spaces => ', isContainOnlySpaces)
console.log('editor containe some text (not only spaces) => ', !!(!isEditorEmpty && lengthOfTrimmedContent))
}

render() {
return (
<div className="container-root">
<Editor
placeholder="Type away :)"
editorState={this.state.editorState}
onChange={this._handleChange}
/>
<button onClick={this._checkEditorContent}>
CHECK
</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>

关于reactjs - 如何检查 draft js Editor 中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47420136/

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