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

React Native中如何高亮当前选中的TextInput组件

解决TextInput聚焦时修改borderColor高亮的问题

你可以通过添加状态跟踪输入框的聚焦状态,再动态调整样式的borderColor属性来实现需求,具体修改如下:

  1. 新增状态变量记录输入框是否聚焦
  2. 在onFocus/onBlur回调中更新聚焦状态
  3. 用数组形式组合基础样式与动态边框样式

修改后的完整代码:

const MainScreen = () => {
   const [pelletWeight, setPelletWeight] = React.useState('');
   // 新增状态跟踪聚焦状态
   const [isFocused, setIsFocused] = React.useState(false);

   const onFocus = () => {
        setIsFocused(true);
    }
    
    const onBlur = () => {
        setIsFocused(false);
    }

    return (
        <View style={styles.root}>
            <TextInput 
                style={[
                    styles.container,
                    // 根据聚焦状态动态切换borderColor
                    { borderColor: isFocused ? '#1677ff' : '#d9d9d9' }
                ]}
                keyboardType='numeric'
                placeholder="Pellet weight (grains)"
                onChangeText={setPelletWeight}
                value={pelletWeight}
                onFocus={onFocus}
                onBlur={onBlur}
            />
        </View>
    )
}

// 示例基础样式,可按需调整
const styles = StyleSheet.create({
    root: {
        flex: 1,
        padding: 16,
    },
    container: {
        height: 44,
        borderWidth: 1,
        borderRadius: 8,
        paddingHorizontal: 12,
        borderColor: '#d9d9d9' // 默认边框色
    }
});

关键说明:

  • 样式数组中后一项会覆盖前一项的同名属性,所以动态borderColor会替换基础样式的默认值
  • 你可以把#1677ff换成任意想要的高亮色,#d9d9d9换成你需要的默认边框色
  • 原代码中onFocus/onBlur未用const声明,在函数组件中会报错,已修正为标准函数声明

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:32:41