React Native 有条件地更改按钮不透明度

Moh*_*h75 4 javascript ecmascript-6 reactjs react-native

我创建了一个浮动操作按钮,我想在到达ScrollView. 所以我用:

<TouchableOpacity
  activeOpacity={0.5}
  onPress={() => {
    this.scrollView.scrollToEnd({ animated: true });
    this.setState({ buttonIsRight: false });
  }}
  style={[
    styles.rightFAB,
    this.state.buttonIsRight ? { opacity: 1 } : { opacity: 0 }
  ]}
>
  <Image
    source={require("../icons/plus.png")}
    style={{
      resizeMode: "center",
      aspectRatio: 1 / 1,
      tintColor: "#888888"
    }}
  />
</TouchableOpacity>;
Run Code Online (Sandbox Code Playgroud)

opacity但一点变化都没有!我设置onPress滚动到结束并更改状态,以便我可以根据该状态更改不透明度。

任何想法?

提前致谢!

Rav*_*Raj 5

当按照您想要的方式更改不透明度时,TouchableOpacity 已经存在问题。

检查此问题页面,https://github.com/facebook/react-native/issues/17105

在react-native核心中修复之前的简单解决方案是将TouchableOpacity的子组件包装在View中并将不透明逻辑应用于该View。

简单的例子,

class App extends React.Component {

  state = {
    opacity: 1
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity>
          {/* Apply opacity logic to the wrapper View */} 
          <View 
            style={{
              backgroundColor: 'grey', 
              opacity: this.state.opacity
            }} 
          >
            <Text>My Button</Text>
          </View>
        </TouchableOpacity>

        <TouchableOpacity
          style={{backgroundColor: 'orange'}}
          onPress={() => this.setState({opacity: !!this.state.opacity? 0 : 1}) }
        >
          <Text>Change opacity</Text>
        </TouchableOpacity>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
});
Run Code Online (Sandbox Code Playgroud)

Snack.expo 中的工作示例:https ://snack.expo.io/r1vMfVg8m

在 iOS 和 Android 上尝试我的工作。谢谢