问题
When a child of a TouchableHighlight has an opacity, its opacity disappears (is set to 1) after the TouchableHighlight is pressed.
Running example here: https://rnplay.org/apps/c0NIjQ
Minimal example:
<TouchableHighlight onPress={() => {}}>
<Text style={{ opacity: 0.5 }}>
Press me!
</Text>
</TouchableHighlight>
Is there a way to mend this, or is it a bug in React Native?
回答1:
TouchableOpacity works as I would have expected for TouchableHighlight (live code sample), so using TouchableOpacity could be a workaround. Note, however, that TouchableOpacity does not have an underlay which appears when active, so whatever you render underneath is what will "shine through" on press. Thus, it's not a perfect substitute for TouchableHighlight.
I'm not sure whether the behavior of TouchableHighlight is intended, some sort of a tradeoff or actually a bug, but looking at the code you can clearly see how it differs from TouchableOpacity in this regard:
- TouchableHighlight always sets the child's opacity to 1 when it goes inactive.
- TouchableOpacity sets the child's opacity to childStyles.opacity if it is set, otherwise 1, when it goes inactive.
回答2:
You could work around it by implementing the onPressOut
method of TouchableHighlight
, and binding your opacity to a state property.
constructor (props) {
this.state = {opacity: 0.5}
}
render () {
return (
<TouchableHighlight
onPressOut={() => this.setState({opacity: 0.5})}
opacity={this.state.opacity}
>
....
</TouchableHighlight>
);
}
Not ideal I agree.
来源:https://stackoverflow.com/questions/41693073/child-of-touchablehighlight-loses-opacity-styling-on-press