如何隐藏React Native中TextInput组件聚焦时的蓝色边框
问题解决方法
核心问题根源
你当前引入的TextInput来自react-native-gesture-handler,该封装组件对React Native原生输入框的属性支持存在兼容缺陷,你遇到的两个问题都和该导入来源有关。
原问题边框效果示例:
具体解决步骤
1. 替换TextInput导入来源
将原有导入语句:
import { TextInput } from "react-native-gesture-handler";
替换为从React Native原生包导入:
import { StyleSheet, TextInput } from "react-native";
替换完成后autoFocus属性即可正常生效。
2. 移除聚焦时的蓝色边框
你看到的蓝色边框属于输入框的聚焦外轮廓,不属于普通border样式,所以修改borderWidth不会生效,给TextInput添加以下属性即可移除:
<TextInput autoFocus={true} placeholder="here is a input" style={{ padding: 4, borderBottomWidth: 2 }} // 新增以下属性 outlineColor="transparent" // 安卓端如果仍有默认下划线可以再加下面这个属性 underlineColorAndroid="transparent" />
如果低版本RN中outlineColor不生效,可以在样式中额外加outline: 'none'。
兜底兼容方案
如果部分场景下autoFocus仍然无法自动触发,可以用ref手动调用聚焦方法:
export default function TabOneScreen() { const inputRef = React.useRef(null); // 组件挂载后手动触发聚焦 React.useEffect(() => { // 加短延时避免页面渲染未完成导致的聚焦失败 setTimeout(() => { inputRef.current?.focus(); }, 100); }, []); return ( <View style={styles.container}> <Text style={styles.title}>Tab One</Text> <View style={styles.separator} lightColor="#eee" darkColor="rgba(255,255,255,0.1)" /> <TextInput ref={inputRef} autoFocus={true} placeholder="here is a input" style={{ padding: 4, borderBottomWidth: 2 }} outlineColor="transparent" /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", }, title: { fontSize: 20, fontWeight: "bold", }, separator: { marginVertical: 30, height: 1, width: "80%", }, });
内容的提问来源于stack exchange,提问作者Weijing Jay Lin
相关产品推荐
相关产品推荐

