Reputation: 27
I have this class that shows two TextInputs, initially the values are empty but then another component send the values by props. The problem is that I also want to edit them in this component but its not working properly. When I receive the values and then I change them, then if I copy them with the Button it wont copy the value in the state. I added a userInitialized and passInitialized booleans that are set to true if the values are changed by typing and not for passing props. Any idea? Thanks.
export default class BotomQRScanner extends Component{
constructor(props){
super(props);
this.state = {
userField: this.props.user,
userInitialized: false,
passInitialized: false,
passwordField: this.props.pass
}
}
handleUserChange(value){
this.setState({userField: value, userInitialized: true});
}
handlePasswordChange(value){
this.setState({passwordField: value, passInitialized: true});
}
render(){
return (
<View style={{height: '100%', width: '100%', alignItems: 'center', justifyContent: 'space-around'}}>
<View style={{flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>
<TextInput
onChangeText={(value) => this.handleUserChange(value)}
style={{textAlign: 'center', fontSize: 16, height: 50, width: 200}}
autoCapitalize = 'none'
autoCorrect={false}
selectTextOnFocus={true}
placeholder={'username'}
selectionColor={'#428AF8'}
value={this.state.userInitialized? this.state.userField : this.props.user}
/>
<Button
title="copy"
onPress={() => {
Clipboard.setString(this.state.userInitialized? this.state.userField : this.props.user)
}}
/>
</View>
<View style={{flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>
<TextInput
onChangeText={(value) => this.handlePasswordChange(value)}
style={{textAlign: 'center', fontSize: 16, height: 80, width: 200}}
autoCapitalize = 'none'
autoCorrect={false}
selectTextOnFocus={true}
placeholder={'password'}
value={this.state.passInitialized? this.state.passField : this.props.pass}
/>
<Button
title="copy"
onPress={() => {
Clipboard.setString(this.state.passInitialized? this.state.passField : this.props.pass)
}}
/>
</View>
</View>
);
}
}
Upvotes: 1
Views: 72
Reputation: 3142
You can change your handleUserChange
and handlePasswordChange
to an arrow function like.
handleUserChange = value => {
this.setState({userField: value, userInitialized: true});
}
AND
handlePasswordChange = value =>{
this.setState({passwordField: value, passInitialized: true});
}
So your functions will get called and your state variable values get updated.
Upvotes: 1