Dynamic Opacity not changing when component rerenders in react native

后端 未结 3 1785
说谎
说谎 2021-01-04 06:31

I\'m starting to learn React Native, and for my project I created a simple Button component to reuse in my project. I set the opacity value dynamically according to the vari

相关标签:
3条回答
  • 2021-01-04 07:11

    If you are using React Native version 0.63 onwards then Pressable is more elegant solution to go with and its Opacity change works as expected.

    <Pressable
        style={{
           opacity: item.isSelected ? 0.5 : 1
        }}>
           //Your button content goes here
    </Pressable>
    
    0 讨论(0)
  • 2021-01-04 07:28

    not sure if it's a bug on the TouchableOpacity component, but the opacity won't update on a re-render until the component is clicked

    to fix your problem just wrap the content of the touchable in a View and apply the opacity to the view instead of the touchable

    export default function Button({text, onPress, style, disabled, textStyle}) {
        const opacity = disabled === true ? 0.5 : 1
        // console.log('opacity', opacity)
        return (
            <TouchableOpacity onPress={onPress} disabled={disabled} 
              style={[defaultStyles.button, style]}>
              <View style={{opacity}}>
                <Text style={[defaultStyles.text, textStyle]}>{text}</Text>
              </View>
            </TouchableOpacity>
        )
    
    }
    
    0 讨论(0)
  • 2021-01-04 07:31

    In my opinion correct solution is to use setOpacityTo method.

    In your render:

    render() {
      const opacityValue = this.props.disabled ? 0.5 : 1;
      return (
        <TouchableOpacity style={{ opacity: opacityValue }} ref={(btn) => { this.btn = btn; }} onPress={this.onPress}>
          <Text>{this.props.text}</Text>
        </TouchableOpacity>
      );
    }
    

    And next you can use setOpacityTo method in componentDidUpdate on disabled props change:

      componentDidUpdate(prevProps) {
        const { disabled } = this.props;
        if (disabled !== prevProps.disabled) {
          const opacityValue = disabled ? 0.5 : 1;
          this.btn.setOpacityTo(opacityValue);
        }
      }
    
    0 讨论(0)
提交回复
热议问题