Reputation: 131
I've been struggling with a weird issue in switch components in React Native when running inside Android app.
Lets say, I have a component which render method looks like this:
render() {
return (
<View>
<View>
<Text>
Test Title
</Text>
<Switch
value={ this.state.value }
onValueChange={
this.test.bind( this )
}
/>
</View>
</View>
);
}
The test
method is:
constructor(props){
super(props);
this.state = {
value: true
};
}
test(){
this.setState( {value: !this.state.value})
}
When I run my module inside my iOS app the onValueChange
method gets called and everything works as expected, however, when I do the same in my Android app the method never gets called when the value is changed to false. What is more, I cannot change the value more than once i.e I can only set the value to false and it will not allow me to set it to true afterwards. The only way I can play with the switch element again is by holding the bar, nonetheless, the value never gets changed (The switch component doesn't change its color) nor the method called .
Has anyone faced something similar? Is this a issue with RN and its Switch component for Android?
I am using:
***NOTE 1: The onValueChange gets called when I put my RN code inside an activity but it fails when it's inside a fragment.
Upvotes: 2
Views: 12651
Reputation: 1497
what works for me is this,
constructor(props) {
super(props)
this.state = {
isOpen : false
}
this.onControlChange = this.onControlChange.bind(this);
}
onControlChange(value) {
return this.setState({
isOpen: !this.state.isOpen
});
}
and in return use this way
render() {
return (
<Switch
onValueChange={this.onControlChange}
value={this.state.isOpen}
/>
)
}
so i believe that you should declare binding for your function in constructor. I tested this for Android emulator only.
Hope this helps.
Upvotes: 0
Reputation: 2248
Try This.
constructor(props){
super(props);
this.state = {
value: true
};
}
and in your render
render() {
return (
<View>
<Text>
Test Title
</Text>
<Switch
value={ this.state.value }
onValueChange={(value) => this.setState({value})}
/>
</View>
);
}
You can remove your test()
function
Upvotes: 4