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

React Native:TextInput数据显示到Text组件时警告的解决方法

问题原因与解决方案

问题根源

警告的核心原因是你初始化phoneNo状态时,错误地将String构造函数赋值给了它,而不是字符串类型的初始值。当React尝试渲染<Text>组件时,会把这个String函数当作子元素处理,而React不允许将函数作为子元素渲染,因此触发警告。

修复步骤

只需要修正LoginUser组件的state初始化代码即可:

将:

this.state ={phoneNo:String};

改为:

this.state ={phoneNo: ''};

修改后的完整代码

class LoginUser extends Component{
    constructor(props){
        super(props);
        this.state ={phoneNo: ''}; // 改为空字符串作为初始值
        this.updatePh = this.updatePhoneNo.bind(this);
    }
    updatePhoneNo(value){
        this.setState({
            phoneNo:value
        })
    }
    render(){
        return(
            <View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
                <TextInput value={this.state.phoneNo} placeholder="Mobile Number" keyboardType="numeric" 
                            onChangeText={(val) =>{this.updatePhoneNo(val)}} returnKeyType ='go'></TextInput>
                <Text>Phone number value :{this.state.phoneNo}</Text>
            </View>
            
        );
    }
}

使用单独组件的情况

如果你继续使用PhoneText组件,只要确保父组件的phoneNo初始值是字符串类型(比如空字符串),组件就能正常渲染,警告也会消失:

class PhoneText extends Component{
    render(){
        return(
            <Text>The Value is {this.props.phoneNumber}</Text>
        );
    }
}

// 在LoginUser的render中正常使用即可
<PhoneText phoneNumber={this.state.phoneNo}></PhoneText>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:46:07