Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何限制草稿js的最大长度_Javascript_Reactjs_Draftjs - Fatal编程技术网

Javascript 如何限制草稿js的最大长度

Javascript 如何限制草稿js的最大长度,javascript,reactjs,draftjs,Javascript,Reactjs,Draftjs,如何限制草稿js中的最大字符数 我可以得到这样的状态长度,但如何停止更新组件 var length = editorState.getCurrentContent().getPlainText('').length; 你应该定义和道具。在处理函数中,检查当前内容的长度+粘贴文本的长度,如果达到最大值,则应返回'handled'字符串 2018年3月21日UPD:升级至react/react dom(16.2.0)和Draft.js(0.10.5)的最新版本。 工作示例- const{Edito

如何限制草稿js中的最大字符数

我可以得到这样的状态长度,但如何停止更新组件

var length = editorState.getCurrentContent().getPlainText('').length;
你应该定义和道具。在处理函数中,检查当前内容的长度+粘贴文本的长度,如果达到最大值,则应返回
'handled'
字符串

2018年3月21日UPD:升级至react/react dom(16.2.0)和Draft.js(0.10.5)的最新版本。

工作示例-

const{Editor,EditorState}=Draft;
const MAX_LENGTH=10;
类容器扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
editorState:editorState.createEmpty()
};
}
render(){
返回(
);
}
_GetLengthofsSelectedText=()=>{
const currentSelection=this.state.editorState.getSelection();
const isCollapsed=currentSelection.isCollapsed();
设长度=0;
如果(!已合并){
const currentContent=this.state.editorState.getCurrentContent();
const startKey=currentSelection.getStartKey();
const endKey=currentSelection.getEndKey();
const startBlock=currentContent.getBlockForKey(startKey);
常量IsStartAndBlockArethesame=startKey==endKey;
const startBlockTextLength=startBlock.getLength();
const startSelectedTextLength=startBlockTextLength-currentSelection.getStartOffset();
const endSelectedTextLength=currentSelection.getEndOffset();
const keyAfterEnd=currentContent.getKeyAfter(endKey);
console.log(当前选择)
如果(启动和阻塞相同){
长度+=currentSelection.getEndOffset()-currentSelection.getStartOffset();
}否则{
让currentKey=startKey;
while(currentKey&¤tKey!==keyAfterEnd){
如果(currentKey==startKey){
长度+=startSelectedTextLength+1;
}else if(currentKey==endKey){
长度+=endSelectedTextLength;
}否则{
长度+=currentContent.getBlockForKey(currentKey.getLength()+1;
}
currentKey=currentContent.getKeyAfter(currentKey);
};
}
}
返回长度;
}
_车把前摆=()=>{
const currentContent=this.state.editorState.getCurrentContent();
const currentContentLength=currentContent.getPlainText(“”).length;
const selectedTextLength=this._getLengthofsselectedText();
如果(currentContentLength-selectedTextLength>MAX_LENGTH-1){
log('最多可以键入十个字符');
返回“已处理”;
}
}
_handlePastedText=(pastedText)=>{
const currentContent=this.state.editorState.getCurrentContent();
const currentContentLength=currentContent.getPlainText(“”).length;
const selectedTextLength=this._getLengthofsselectedText();
如果(currentContentLength+pastedText.length-selectedTextLength>最大长度){
log('最多可以键入十个字符');
返回“已处理”;
}
}
_handleChange=(编辑状态)=>{
this.setState({editorState});
}
}
ReactDOM.render(,document.getElementById('react-root'))

Mikhail的方法是正确的,但处理程序返回值是错误的。”“not_handled”是一个失败案例,允许编辑器组件正常处理输入。在本例中,我们希望停止编辑器处理输入

在旧版本的DraftJS中,处理代码中似乎存在一个计算为“true”的字符串,因此上述代码的行为正确。在更高版本的DraftJS中,上面的提琴不起作用-我没有名声在这里发布更多的提琴,但请尝试Mikhail的代码与DraftJS的v0.10进行复制

若要更正此问题,请在不希望编辑器继续处理输入时返回“handled”或true

比如说,

_handleBeforeInput = () => {
  const currentContent = this.state.editorState.getCurrentContent();
  const currentContentLength = currentContent.getPlainText('').length

  if (currentContentLength > MAX_LENGTH - 1) {
    console.log('you can type max ten characters');
    return 'handled';
  }
}

有关更多信息,请参阅可取消处理程序上的DraftJS文档。

让我们考虑一下。进行更改需要什么?你的
onChange
,对吗?好。我们也知道
长度
。对的我们附加“worker”,即更改后的
onChange

const length = editorState.getCurrentContent().getPlainText('').length;

// Your onChange function:   
onChange(editorState) {
 const MAX_LENGTH = 10;
 const length = editorState.getCurrentContent().getPlainText('').length;

 if (length <= MAX_LENGTH) {
  this.setState({ editorState }) // or this.setState({ editorState: editorState })
 }
} else {
 console.log(`Sorry, you've exceeded your limit of ${MAX_LENGTH}`)
}
const length=editorState.getCurrentContent().getPlainText(“”).length;
//您的onChange函数:
onChange(编辑状态){
const MAX_LENGTH=10;
const length=editorState.getCurrentContent().getPlainText(“”).length;

如果(length这是一个有点旧的线程,但是我想我会为其他面临粘贴文本时字符限制和行为问题的人分享一个解决方案

基于Mikhail的上述代码,我很快就完成了一些工作,来处理这个对我来说很有用的用例——尽管我还没有做过任何优化工作

基本上,句柄粘贴的文本如下所示:

      const __handlePastedText = (pastedText: any) => {
        const currentContent = editorState.getCurrentContent();
        const currentContentLength = currentContent.getPlainText('').length;
        const selectedTextLength = _getLengthOfSelectedText();
    
        if (currentContentLength + pastedText.length - selectedTextLength > MAX_LENGTH) {
            const selection = editorState.getSelection()
            const isCollapsed = selection.isCollapsed()
            const tempEditorState = !isCollapsed ? _removeSelection() : editorState
            _addPastedContent(pastedText, tempEditorState)
          return 'handled';
        }
        return 'not-handled'
      }
我们有一个助手函数,用于在粘贴新字符(返回新编辑器状态)之前处理选择的删除:

      const _removeSelection = () => {
        const selection = editorState.getSelection()
        const startKey = selection.getStartKey()
                const startOffset = selection.getStartOffset()
                const endKey = selection.getEndKey()
                const endOffset = selection.getEndOffset()
                if (startKey !== endKey || startOffset !== endOffset) {
                    const newContent = Modifier.removeRange(editorState.getCurrentContent(), selection, 'forward')
                    const tempEditorState = EditorState.push(
                        editorState,
                        newContent,
                        "remove-range"
                    )
                    setEditorState(
                        tempEditorState
                    )
                    return tempEditorState
                }
                return editorState
      }
最后是添加带有限制的粘贴文本的函数:

      const _addPastedContent = (input: any, editorState: EditorState) => {
        const inputLength = editorState
        .getCurrentContent()
        .getPlainText().length;
        let remainingLength = MAX_LENGTH - inputLength;

        const newContent = Modifier.insertText(
            editorState.getCurrentContent(),
            editorState.getSelection(),
            input.slice(0,remainingLength)
        ); 
        setEditorState(
            EditorState.push(
                editorState,
                newContent,
                "insert-characters"
            )
        )
      }
链接到工作示例:

突出显示某些当前内容并粘贴以覆盖突出显示的内容的用例如何?@Devnjs很好,谢谢!最初没有提供此用例。我更新了答案,目前,我们在将某些内容粘贴到编辑器时会检查所选文本的长度。@MikhailShabrikov-您可能想检查sele插入单个字符时的字符长度。目前您不允许选择所有文本并按键,但允许粘贴。@谢谢您的代码名,这一点很好。我已经修复了它,请检查更新的小提琴。@MikhailShabrikov您还创建了一些以后不使用的常量(例如
isBackward
)–有什么正当的理由吗?没有,onchange的工作只是设置状态,它会因为editorstate中的任何类型的更改而发生冲突,而不仅仅是额外的字符。
      const _addPastedContent = (input: any, editorState: EditorState) => {
        const inputLength = editorState
        .getCurrentContent()
        .getPlainText().length;
        let remainingLength = MAX_LENGTH - inputLength;

        const newContent = Modifier.insertText(
            editorState.getCurrentContent(),
            editorState.getSelection(),
            input.slice(0,remainingLength)
        ); 
        setEditorState(
            EditorState.push(
                editorState,
                newContent,
                "insert-characters"
            )
        )
      }