如何检查草稿js编辑器中的空格

IT技术 reactjs draftjs
2021-05-23 04:26:37

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

contentState.hasText()
2个回答

您可以使用两种方法检查编辑器内容,您可以在当前内容状态上调用这些方法。第一个 - 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>

您可以使用 String.trim() 删除所有跳转和空格,然后只需检查长度:

if (content.getPlainText().trim().length == 0) {
  updateYourVariableToNull()
}

或者如果您使用的是 EditorState:

editorState.getCurrentContent().getPlainText().trim().length