You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何单独设置输入框背景透明度不影响文本?

解决React Native TextInput背景透明但文本不透明的问题

要实现背景透明度0.5、文本完全不透明的效果,别用opacity属性(它会让整个组件包括文本都变透明),直接用rgba格式的颜色值设置背景色就行:

  1. 先把你原来的十六进制颜色#90B0DD转换成RGB值:144, 176, 221
  2. 把backgroundColor改成rgba(144, 176, 221, 0.5),最后一个参数就是透明度(取值范围0到1)

修改后的样式代码

const styles = StyleSheet.create({
   container: {
       height: '100%',
       backgroundColor: '#F1F6FA',
   },

   input: {
       width: '90%',
       alignSelf: 'center',
       marginTop: 20,
       height: 80,
       borderRadius: 30,
       borderWidth: 1,
       textAlign: 'center',
       // 改用rgba格式,仅背景透明,文本不受影响
       backgroundColor: 'rgba(144, 176, 221, 0.5)',
       fontSize: 26,
       fontWeight: 'bold',
   },
})

完整组件代码

import { useState, View, TextInput, StyleSheet } from 'react';
import CalculateDiscount from '../calculate-discount/CalculateDiscount';


const Discount = () => {

   const [price, setPrice] = useState(0);
   const [discount, setDiscount] = useState(0);

   return (
       <View style={styles.container}>
           <TextInput style={styles.input}
               placeholder='enter price'
               keyboardType='numeric'
               value={price.toString()}
               onChangeText={(value) => setPrice(Number(value))}
           />
           <TextInput style={styles.input}
               placeholder='enter discount %'
               keyboardType='numeric'
               value={discount.toString()}
               onChangeText={(value) => setDiscount(Number(value))}
           />

           <CalculateDiscount price={price} discount={discount}/>
       </View>
   )
}

const styles = StyleSheet.create({
   container: {
       height: '100%',
       backgroundColor: '#F1F6FA',
   },

   input: {
       width: '90%',
       alignSelf: 'center',
       marginTop: 20,
       height: 80,
       borderRadius: 30,
       borderWidth: 1,
       textAlign: 'center',
       backgroundColor: 'rgba(144, 176, 221, 0.5)',
       fontSize: 26,
       fontWeight: 'bold',
   },
})

export default Discount;

额外说明:原代码中useState初始值是数字类型,但TextInput的value要求为字符串,所以添加了.toString()转换,避免控制台警告。

内容的提问来源于stack exchange,提问作者Tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 04:49:56