React Native修改TextInput文字颜色时输入内容被清空问题咨询
问题原因及解决方案
这是操作有误,不是Bug。
你的代码存在两个关键问题:
- 没有给
TextInput绑定输入值状态,当调用setFocusInputTextColor更新颜色时,组件重新渲染,TextInput因缺少受控的value属性会回到初始空状态,导致输入内容被清空。 - 初始的
focusInputTextColor值缺少#前缀,会导致颜色样式失效。
修正后的代码如下:
import { useState } from 'react'; import { TextInput, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ input: { borderWidth: 1, padding: 10, backgroundColor: '#333' // 示例背景色,方便查看白色文字效果 } }); function YourComponent() { // 修正初始颜色的#前缀 const [focusInputTextColor, setFocusInputTextColor] = useState("#000000"); // 添加状态保存输入内容 const [inputValue, setInputValue] = useState(""); const onFocusInput = () => { setFocusInputTextColor('#ffffff'); }; const onBlurInput = () => { setFocusInputTextColor('#000000'); }; return ( <TextInput style={[styles.input, { color: focusInputTextColor }]} // 绑定输入值与更新逻辑 value={inputValue} onChangeText={(text) => setInputValue(text)} placeholder="Placeholder here" placeholderTextColor="#000000" onFocus={onFocusInput} onBlur={onBlurInput} /> ); }
关键修改说明:
- 新增
inputValue状态存储输入内容,并绑定到TextInput的value属性,确保组件重渲染时保留输入值。 - 调整
onChangeText逻辑,用于更新输入值状态,而非仅打印日志。 - 修正初始颜色值的格式,添加
#前缀保证样式生效。
内容的提问来源于stack exchange,提问作者Quantal
相关产品推荐
相关产品推荐

