Child of TouchableHighlight loses opacity styling on press

て烟熏妆下的殇ゞ 提交于 2019-12-10 18:39:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!