React Native中如何高亮当前选中的TextInput组件
解决TextInput聚焦时修改borderColor高亮的问题
你可以通过添加状态跟踪输入框的聚焦状态,再动态调整样式的borderColor属性来实现需求,具体修改如下:
- 新增状态变量记录输入框是否聚焦
- 在
onFocus/onBlur回调中更新聚焦状态 - 用数组形式组合基础样式与动态边框样式
修改后的完整代码:
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
相关产品推荐
相关产品推荐

