React Native - setting the position of the TextInput cursor

In my React Native application, I am trying to set the cursor position TextInputto a certain position (for example, to the 5th character), but I have problems with this, since the documentation is not enough. I suspect this has something to do with the setSelection property for TextInput, but I cannot figure out what to do.

Has anyone successfully done this?

Thanks.

+7
source share
5 answers

Since @ this.lau_ says there is a controller property called selectionthat takes an object with the start and end of the keys.

Example:

class ControlledSelectionInput extends Component {
    state = {
        selection: {
            start: 0,
            end: 0
        }
    }

    // selection is an object: { start:number, end:number }
    handleSelectionChange = ({ nativeEvent: { selection } }) => this.setState({ selection })

    render() {
        const { selection } = this.state;

        return <TextInput selection={selection} onSelectionChange={this.handleSelectionChange} />
    }
}

, setNativeProps :

this.inputRef.setNativeProps({ selection:{ start:1, end:1 } })

:

class SetNativePropsSelectionInput extends Component {
    inputRef = null

    render() {
        const { selection } = this.state;

        return (
            <View>
                <TextInput ref={this.refInput} />
                <Button title="Move selection to start" onPress={this.handleMoveSelectionPress} />
            </View>
    }

    refInput = el => this.inputRef = el

    handleMoveSelectionPress = () => this.input.setNativeProps({
        selection: {
            start: 0,
            end: 0
        }
    })
}
+5

TextInput selection, /.

+3

:

public static void adjustCursor(EditText dgInput) {
    CharSequence text = dgInput.getText();
    if (text instanceof Spannable && text.length() > 0) {
        Spannable spanText = (Spannable) text;
        Selection.setSelection(spanText, text.length());
    }
}

, React Native.

0

, ,

,

class YourComponent extends React.Component{
      constructor(props) {
       super(props);
       this.state = {
       text:'Hello World',
       selection: {
        start: 0,
        end: 0
       }
  };

this.inputRefs = {};
}

   setSelection = () => {
      this.setState({ select: { start: 1, end: 1 } });
      };

    changeText = (val) => {
     this.inputRefs.input.focus();
    }

    render(){
       return(
          <TextInput 
            onFocus={this.setSelection}
            selection={this.state.setSelection} 
            onChangeText={val => {this.changeText(val)}} 
            value={this.state.text}
             refName={ref => {
             this.inputRefs.input = ref;
             }}
            />
       )
    }
} 

, , TextInput onChangeText, TextInput , onFocus, .

0

Source: https://habr.com/ru/post/1615694/


All Articles