How to disable highlighting effect of TouchableOpacity when scrolling?

岁酱吖の 提交于 2019-12-08 01:43:14

问题


<TouchableOpacity style={{ flex: 1 }} >
  <ImageBackground
    source={require('../../images/home.jpg')}>
      <View style={styles.item} collapsable={false}>
        <H3>{contentData[i].name}</H3>
        <Text>{contentData[i].description}</Text>
      </View>
  </ImageBackground>
</TouchableOpacity>

I have a list of TouchableOpacity inside a ScrollView. I want to disable highlighting effect of TouchableOpacity. When scrolling I want to highlight only when onPress event is triggered. Because it may confuse the user that it is pressed.


回答1:


You can make use of onScrollBeginDrag and onScrollEndDrag props.

 state = {
    scrollBegin: false
  }

  scrollStart = () => this.setState({scrollBegin: true})   
  scrollEnd = () => this.setState({scrollBegin: false})

 <ScrollView onScrollBeginDrag={this.scrollStart} onScrollEndDrag={this.scrollEnd}>
   ... Other stuff
 </ScrollView>

and set activeOpacity={1} for TouchableOpacity when this.state.scrollBegin=true




回答2:


Try setting the activeOpacity prop on the TouchableOpacity to 1 when scrolling. Use default settings when the user stops scrolling.

https://facebook.github.io/react-native/docs/touchableopacity#activeopacity




回答3:


I had the same issue, so I wrote this class that I use instead of <TouchableOpacity> in my code:

import React, { Component } from 'react';
import { TouchableOpacity } from 'react-native';
import TimerMixin from 'react-timer-mixin';

class TouchableOpacityScrollable extends Component {
  _onPress() {
    const { onPress } = this.props;

    // Looking in the TouchableOpacity source code we see that
    // the touch Opacity is 150, and that it comes back in 250 milliseconds.
    // @see https://github.com/facebook/react-native/blob/c416b40542ece64e26fb2298485ae42eeebc352a/Libraries/Components/Touchable/TouchableOpacity.js
    this.refs.touchableOpacity.setOpacityTo(0.2, 150);

    TimerMixin.setTimeout(() => {
      onPress();
      this.refs.touchableOpacity.setOpacityTo(1, 250);
    }, 150);
  }

  render() {
    const { style, children } = this.props;

    return (
      <TouchableOpacity
        ref="touchableOpacity"
        style={style}
        activeOpacity={1.0}
        onPress={() => this._onPress()}
      >
        {children}
      </TouchableOpacity>
    );
  }
}

export default TouchableOpacityScrollable;

You will have to install react-timer-mixin to prevent possible crashes.

Enjoy!




回答4:


Simply pass activeOpactity prop with value 1.

<TouchableOpacity activeOpacity={1}>....</TouchableOpacity>

Make sure you import TouchableOpacity from "react-native" not from "react-native-gesture-handler".



来源:https://stackoverflow.com/questions/52421283/how-to-disable-highlighting-effect-of-touchableopacity-when-scrolling

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