React Native - 设置TextInput游标位置

col*_*fet 9 android ios react-native

在我的React Native应用程序中,我正在尝试将a的光标位置设置TextInput为特定位置(例如,设置为第5个字符),但由于文档缺少一点,我很难这样做.我怀疑它与'setSelection'属性有关,TextInput但我似乎无法找到该做什么.

有没有人成功这样做过?

谢谢.

Noi*_*art 13

正如@ this.lau_所说,有一个控制器属性被调用selection,它接受一个带有键start和end的对象.

例:

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} />
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以通过获取组件的引用并以setNativeProps如下方式使用以编程方式设置选择:

this.inputRef.setNativeProps({ selection:{ start:1, end:1 } })
Run Code Online (Sandbox Code Playgroud)

例:

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
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

  • `setNativeProps` 似乎在 iOS 和 Android 上都运行良好。唯一的问题是,它会导致选择是永久性的。到目前为止,在“setNativeProps”之后使用“setTimeout(() =&gt; this.inputRef.setNativeProps({ Selection: null }), 0)”似乎可以在选择后将选择切换回不受控制的状态。不过,这很老套,所以我认为使用 `selection` 属性可能会更好,尽管 API 不太适合声明式选择。 (3认同)

lau*_*ent 7

现在有一个选择属性TextInput,可用于设置选择或插入符号/光标位置。


tin*_*ght 0

我只知道原生方式:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

也许你可以在 React Native 中找到相同的方法。