You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Paper:页面加载时让第二个TextInput获焦并选中内容

实现第二个TextInput自动获焦并选中内容的方案

针对你的需求,结合React钩子和react-native-paper的API,可按以下步骤修改代码:

  1. 导入useRef和useEffect钩子:用于创建输入框引用,以及处理组件挂载后的操作
  2. 生成输入框引用:绑定到第二个TextInput上
  3. 组件挂载后执行操作:调用输入框的focus()和select()方法,实现获焦并选中内容
  4. 修正value类型:TextInput的value建议使用字符串类型,避免类型不匹配问题

修改后的完整代码:

import { StyleSheet, View } from 'react-native';
import { TextInput } from 'react-native-paper';
import { useRef, useEffect } from 'react';

export default function App() {
  // 创建第二个输入框的引用
  const secondInputRef = useRef(null);

  useEffect(() => {
    // 页面加载完成后,执行获焦和选中操作
    if (secondInputRef.current) {
      secondInputRef.current.focus();
      secondInputRef.current.select();
    }
  }, []); // 空依赖数组确保只在组件挂载后执行一次

  return (
    <View style={{ flex: 1, padding: 20, justifyContent: 'center' }}>
      <TextInput
        value="1"
        style={{ marginBottom: 10 }}
      />
      <TextInput
        ref={secondInputRef}
        value="2"
      />
    </View>
  );
}

const styles = StyleSheet.create({});

关键细节说明:

  • useRef:函数组件中不能使用this.ref,必须通过useRef创建并保存组件引用
  • useEffect空依赖:保证回调仅在组件首次渲染完成后执行,匹配"页面加载完成"的触发时机
  • focus() & select():react-native-paper的TextInput继承了原生组件的这两个方法,分别实现获取焦点和选中全部内容的功能

内容的提问来源于stack exchange,提问作者araraujo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 07:37:05