如何在反应原生的条件渲染中更改按钮的不透明度

问题描述

我是本机反应的新手。我创建了一个表格。其中我根据服务器响应呈现一些按钮。现在我想将按钮的不透明度设置为 50%。我希望那个按钮现在看起来像一个禁用的。所以有可能吗,如果是的话,请帮忙。谢谢。我想在我的第一行代码中设置不透明度

这是我的代码

 {data.bank_account_details_data[0] != null && ( 

              <TouchableOpacity>
                <Card center middle shadow style={styles.category} >
                  OTHER informatION
                  </Text>
                </Card>
              </TouchableOpacity>

              )}

解决方法

您可以根据 style 属性中的条件使用三元表达式(如您的第一行)设置 TouchableOpacity 的不透明度。

简化示例:

export default function App() {
  const [hasOpacity,setHasOpacity] = React.useState(false)

  return (
    <View style={styles.container}>
      <TouchableOpacity onPress={() => {
        setHasOpacity(!hasOpacity)
      }} 
      activeOpacity={0.2}
      style={{opacity: hasOpacity ? 0.5 : 1.0}}
      >
      <Text>Test</Text></TouchableOpacity>
    </View>
  );
}

https://snack.expo.io/a1Y-TU4XB

在您的示例中,它可能如下所示:

<TouchableOpacity 
      activeOpacity={0.2}
      style={{opacity: data.bank_account_details_data[0] != null ? 0.5 : 1.0}}
      >
,

你可以使用这样的东西

<TouchableOpacity 
   // opacity value ranges from 0 to 1
    activeOpacity={0.9}  //opacity for on touch behaviour
    style={{opacity:0.9}} // opacity for view behaviour
    onPress={()=>{
      console.log("i am here")
    }}>
      <Text style={{color:"#FFF"}}>This is opacity check</Text>
    </TouchableOpacity>

除了不透明度的静态值,您还可以使用后端的状态、道具或值作为变量