Reputation: 1716
I'm currently attempting to change the borderColor of a single Textinput element, using the prop onFocus. I'm using an array that contains two sets of styles, the first one "styles.textInput" should be the first one that is loaded. The second should only load when toggle is true and then it should load the second style which is "styles.textInputAlt"
Right now, the borderColor of BOTH textInputs are changing. How do I make sure that the only textInput that gets changes is the one that's currently onFocus?
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 = {
toggle: false,
}
}
hasFocus(){
this.setState({
toggle: !this.state.toggle
})
}
lostFocus(){
this.setState({
toggle:this.state.toggle,
})
}
render(){
return(
<View style={styles.container}>
<TextInput
style={[styles.textInput, this.state.toggle && styles.textInputAlt]}
onFocus={()=>this.hasFocus()}
onBlur={()=>this.lostFocus()}
/>
<TextInput
style={[styles.textInput, this.state.toggle && styles.textInputAlt]}
onFocus={()=>this.hasFocus()}
onBlur={()=>this.lostFocus()}
/>
</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'
}
});
Upvotes: 2
Views: 3212
Reputation: 21
an easy way to solve your situation is to use parameters, here's a very basic example:
//Methods
handlerFocus = (input) => {
this.setState({
[input]:true
});
};
handlerBlur = (input) => {
this.setState({
[input]:false
});
};
// In render method
<TextInput
style= {[
styles.textInput,
this.state.nameInputOneFocus?styles.textInputFocus:''
]}
onFocus = {() => this.handlerFocus('nameInputOneFocus')}
onBlur = {() => this.handlerBlur('nameInputOneFocus')}
/>
<TextInput
style= {[
styles.textInput,
this.state.nameInputTwoFocus?styles.textInputFocus:''
]}
onFocus = {() => this.handlerFocus('nameInputTwoFocus')}
onBlur = {() => this.handlerBlur('nameInputTwoFocus')}
/>
Upvotes: 2
Reputation: 2333
Your code, while correct, has one problem. You are tracking whether any text input is focused or not, however you should be tracking this.state.toggle
for each text input seperately (toggle1 and toggle2, if you will). Because of this, when you focus anything your application updates state and since both text inputs decide their color based on this.state.toggle
they both change their color.
Upvotes: 0