React Native中如何通过onFocus仅修改单个TextInput的borderColor
问题分析
你现在的问题核心在于两个TextInput共用了同一个toggle状态变量——不管哪个输入框触发聚焦/失焦,都会修改这个全局状态,导致两个输入框的样式同时变化。要实现仅当前聚焦的输入框变色,我们需要单独跟踪每个输入框的聚焦状态,或者记录当前正在聚焦的输入框标识。
解决方案:跟踪当前聚焦的输入框ID
我们可以把状态从单个toggle改成记录当前聚焦输入框的ID(比如字符串或数字),然后在渲染每个输入框时,判断它的ID是否和状态里的一致,再决定是否应用高亮样式。
修改后的完整代码
import React, {Component} from 'react'; import { AppRegistry, StyleSheet, Text, TextInput, TouchableHighlight, View, } from 'react-native'; export default class Highlight extends Component{ constructor(){ super() this.state = { focusedInputId: null, // 用这个变量记录当前聚焦的输入框ID } } // 聚焦时传入当前输入框的ID handleFocus = (inputId) => { this.setState({ focusedInputId: inputId }) } // 失焦时清空聚焦ID handleBlur = () => { this.setState({ focusedInputId: null }) } render(){ return( <View style={styles.container}> {/* 给第一个输入框指定ID为'input1',判断是否等于当前聚焦ID */} <TextInput style={[styles.textInput, this.state.focusedInputId === 'input1' && styles.textInputAlt]} onFocus={()=>this.handleFocus('input1')} onBlur={this.handleBlur} /> {/* 第二个输入框指定ID为'input2' */} <TextInput style={[styles.textInput, this.state.focusedInputId === 'input2' && styles.textInputAlt]} onFocus={()=>this.handleFocus('input2')} onBlur={this.handleBlur} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }, textInput: { borderColor: '#000', borderWidth: 2.0, backgroundColor: '#fff', height: 40, marginLeft: 60, marginRight: 60, marginBottom: 30, padding: 2, }, textInputAlt: { borderColor: '#e71636', }, button: { height: 50, backgroundColor: '#48bbec', alignSelf: 'stretch', marginTop: 10, marginLeft: 60, marginRight: 60, justifyContent: 'center' }, buttonText: { fontSize: 22, color: '#FFF', alignSelf: 'center' } });
关键改动说明
- 状态变量调整:把
toggle换成focusedInputId,初始值为null,表示没有输入框聚焦。 - 聚焦/失焦方法优化:
handleFocus接收一个inputId参数,用来标记当前聚焦的输入框;handleBlur则把focusedInputId重置为null。 - 样式判断逻辑:每个TextInput的style数组里,判断自身的ID是否等于
state.focusedInputId,只有匹配时才应用styles.textInputAlt样式。
这样就能保证只有当前正在聚焦的那个TextInput会改变边框颜色,其他输入框保持默认样式啦。
内容的提问来源于stack exchange,提问作者VK1
相关产品推荐
相关产品推荐

