Cuando hago clic en un botón con un símbolo determinado, me gustaría colocar el símbolo en el campo de texto.
Para lograr eso, uso una función para la inserción de texto:
insertText(characterToInsert) { let editorState = this.state.editorState; const currentContent = editorState.getCurrentContent(), currentSelection = editorState.getSelection(); let newContent = Modifier.replaceText( currentContent, currentSelection, characterToInsert ); return EditorState.push(editorState, newContent, 'insert-characters'); }Me gustaría poner un texto de subíndice allí cuando el estilo en línea de subíndice está activado.
Traté de hacer algo como
if (this.isSubscriptOn()) { newContent = Modifier.applyInlineStyle(newContent, currentSelection, 'SUBSCRIPT'); }sin embargo, no sé cómo modificar el segundo argumento para que la selección apunte a los caracteres recién colocados.
¿Hay una mejor manera de abordar esto?
El primer paso es usar la applyInlineStyle: function (contentState: ContentState, selectionState: SelectionState, inlineStyle: string) de la clase Modifier estática. Como puede ver, requiere una selección del área a la que queremos que se aplique nuestro estilo. Crearemos dicho estilo usando el método set de immutable.js :
const textToInsertSelection = currentSelection.set('focusOffset', currentSelection.getFocusOffset() + textToInsert.length); Luego obtendremos el OrderedSet de estilos en línea actuales y aplicaremos cada uno de ellos a la selección mencionada anteriormente:
let inlineStyles = editorState.getCurrentInlineStyle(); inlineStyles.forEach(inLineStyle => newContent = Modifier.applyInlineStyle(newContent, textToInsertSelection, inLineStyle));Si nos detenemos aquí, el texto se colocará en el campo de entrada mientras se selecciona (aparecerá un rectángulo azul a su alrededor). Para evitar tal comportamiento, fuercemos una selección al final del texto insertado:
newState = EditorState.forceSelection(newState, textToInsertSelection.set('anchorOffset', textToInsertSelection.getAnchorOffset() + textToInsert.length));Toda la función se ve así:
insertText(textToInsert) { let editorState = this.state.editorState; const currentContent = editorState.getCurrentContent(); const currentSelection = editorState.getSelection(); let newContent = Modifier.replaceText( currentContent, currentSelection, textToInsert ); const textToInsertSelection = currentSelection.set('focusOffset', currentSelection.getFocusOffset() + textToInsert.length); let inlineStyles = editorState.getCurrentInlineStyle(); inlineStyles.forEach(inLineStyle => newContent = Modifier.applyInlineStyle(newContent, textToInsertSelection, inLineStyle)); let newState = EditorState.push(editorState, newContent, 'insert-characters'); newState = EditorState.forceSelection(newState, textToInsertSelection.set('anchorOffset', textToInsertSelection.getAnchorOffset() + textToInsert.length)); return newState; }