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

React-Native中PhoneInput输入号码后UI不显示值的问题求助

解决react-native-phone-number-input输入值不显示的问题

核心问题修正:用value替代defaultValue

你当前代码里使用的defaultValue={phoneNumber}是初始值属性,仅在组件首次渲染时生效,后续状态更新不会同步到输入框UI。正确的做法是用value属性绑定当前的格式化号码状态,确保UI随状态变化实时更新:

修改后的完整代码:

import React, {useState} from 'react';
import { View } from 'react-native'; // 补充你遗漏的View组件导入
import PhoneInput from 'react-native-phone-number-input';

const ComPhoneInput = () => {
  const [phoneNumber, setPhoneNumber] = useState('');
  const [phoneValue, setPhoneValue] = useState('');

  return (
    <View style={styles.phoneContainerStyle}>
      <PhoneInput
        value={phoneNumber} // 替换defaultValue为value
        defaultCode="BD"
        placeholder="01770019346"
        onChangeFormattedText={inputValue => {
          setPhoneNumber(inputValue);
        }}
        onChangeText={pValue => {
          setPhoneValue(pValue);
        }}
        containerStyle={styles.phoneMainStyle}
        textContainerStyle={styles.phoneTextMainStyle}
        textInputStyle={styles.phoneTextStyle}
      />
    </View>
  );
};

export default ComPhoneInput;

额外排查点

  • 检查样式冲突:确认textInputStyle中没有设置color为透明或与背景色一致,导致输入文字不可见。可临时添加color: '#000'测试:
    textInputStyle={{...styles.phoneTextStyle, color: '#000'}}
    
  • 升级组件版本:旧版本组件可能存在已知bug,执行命令升级到最新版:
    npm update react-native-phone-number-input
    
  • 精简冗余状态:如果不需要原始未格式化的号码,可删除phoneValue状态,减少状态管理复杂度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:03:18