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

React Native修改TextInput文字颜色时输入内容被清空问题咨询

问题原因及解决方案

这是操作有误,不是Bug。

你的代码存在两个关键问题:

  1. 没有给TextInput绑定输入值状态,当调用setFocusInputTextColor更新颜色时,组件重新渲染,TextInput因缺少受控的value属性会回到初始空状态,导致输入内容被清空。
  2. 初始的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:55:33