【问题标题】:How to check empty spaces in draft js Editor如何检查草稿js编辑器中的空格
【发布时间】:2017-11-21 18:24:58
【问题描述】:

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

contentState.hasText()

【问题讨论】:

  • 当编辑器内容只有空格字符而没有字母时,你会处理这种情况吗?如果您的编辑器有foo bar 文本,是否应该在这种情况下提交表单?
  • 我的意思是当编辑器只有空格没有任何字符。

标签: reactjs draftjs


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    或者如果您使用的是 EditorState:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      相关资源
      最近更新 更多