React Native 组件挂载后如何自动聚焦TextInput 初始化时即让TextInput聚焦
React Native无状态组件中TextInput初始化自动聚焦解决方案
方案1:使用原生autoFocus属性(最简单通用)
TextInput自带的autoFocus属性默认会在组件挂载完成后自动触发聚焦,直接设置即可满足绝大多数场景需求,示例代码如下:
import React from 'react'; import { TextInput, View } from 'react-native'; const MyInputComponent = () => { return ( <View> <TextInput placeholder="请输入内容" autoFocus={true} style={{ height: 40, borderColor: 'gray', borderWidth: 1 }} /> </View> ); }; export default MyInputComponent;
方案2:useRef + useEffect手动控制(适合自定义场景)
如果需要条件聚焦、延迟聚焦,或者autoFocus在你的场景(比如嵌套弹窗、路由跳转页面)下失效,可以手动通过引用调用focus方法:
import React, { useRef, useEffect } from 'react'; import { TextInput, View } from 'react-native'; const MyInputComponent = () => { // 创建TextInput的引用 const inputRef = useRef<TextInput>(null); // 组件挂载完成后执行聚焦 useEffect(() => { // 加可选链判断防止引用为空报错 inputRef.current?.focus(); }, []); return ( <View> <TextInput ref={inputRef} placeholder="请输入内容" style={{ height: 40, borderColor: 'gray', borderWidth: 1 }} /> </View> ); }; export default MyInputComponent;
注意事项
- 同一页面不要给多个TextInput设置
autoFocus={true},只会最后一个生效,会出现冲突 - 弹窗/模态框场景下
autoFocus容易失效,优先选择方案2手动触发聚焦 - 部分安卓机型如果出现聚焦成功但软键盘不弹出的情况,可以在调用focus后配合
Keyboard模块手动调用Keyboard.show()
内容的提问来源于stack exchange,提问作者user16244117
相关产品推荐
相关产品推荐

