React Native中如何单独设置输入框背景透明度不影响文本?
解决React Native TextInput背景透明但文本不透明的问题
要实现背景透明度0.5、文本完全不透明的效果,别用opacity属性(它会让整个组件包括文本都变透明),直接用rgba格式的颜色值设置背景色就行:
- 先把你原来的十六进制颜色
#90B0DD转换成RGB值:144, 176, 221 - 把
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
相关产品推荐
相关产品推荐

