自动完成编辑器(REACT,DRAFT-JS)

时间:2019-08-26 09:41:29

标签: javascript reactjs autocomplete editor draftjs

我做完作业,但不知道该怎么办。进行DRAFT-JS编辑器以显示自动完成项非常简单。使用键盘自动完成插补(不在代码中)。 但是我在更改状态编辑器时遇到问题。 这是一尘不染的代码版本,请帮助我。

我尝试了一些草稿js组件来实现自动完成,但是很烂 等待我在键盘上的等待。 我认为这是一个聪明的解决方案,但我坚持这一点。

import React, { Component } from 'react';
import './testing.css';
import { Editor, EditorState, ContentState, convertToRaw } from 'draft-js';

 export default class Autocomplete extends React.Component {
 constructor (props){
    super(props);
 this.items=[
    "Test1",
    "Home",
    "Gold",
    "Miner",
    "Team",
    "Tenis",
 ];

    this.state = {
        suggestions: [],
        search: "",
        replace: "",
        testBool: false,
        editorState: EditorState.createEmpty()
    };
 }
        onTextChange = (editorState) => {


            var contentState = this.state.editorState.getCurrentContent();

            const editorContentRaw = convertToRaw(contentState);//Returning some values equals to bullshit
            const value =(editorContentRaw.blocks[0].text);
            console.log('editor test: '+ value);//Return value of editor

            const values=value.split(" ");//Get values to array

            let suggestions = [];
            if(value.length > 0){
                const regex = new RegExp(`^${value}`, 'i');
                 suggestions = this.items.sort().filter(v => regex.test(v));
            }

           this.setState(() => ({suggestions, editorState }));


        }



        suggestionSelected(value){
            this.setState(() => ({
                suggestion: [],


            }));

        }


        renderSuggestion (){
        const {suggestions} = this.state;
        if (suggestions.length === 0){
            return null;
            }

            return(
                <ul>
                 {suggestions.map((item) => <li onClick = {() => this.suggestionSelected(item)}> {item}</li>)}

                </ul>

        );
    }

    render() {

        return (
            <div  class="AutoCompleteText">
               <Editor onChange={this.onTextChange} editorState={this.state.editorState}/> 
                 {this.renderSuggestion()}

            </div>
        );
    }
}

1 个答案:

答案 0 :(得分:0)

let trigger=false; //Triger for show/hide suggestions
window.addEventListener("keydown", event => { //event listener for keyboard shortcut
    if (event.ctrlKey && event.which === 32) {
      trigger = (!trigger); //switching true and false values
    }

  });

需要在主要组件之前。我知道了。