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

React Native 如何将子组件TextInput的输入值传递给父组件

代码调整方案

核心问题点

  • 函数式子组件的入参接收方式错误,未正确解构props对象
  • React Native的TextInput的onChangeText回调直接返回输入字符串,不需要读取target.value属性
  • 受控组件模式下子组件不需要额外维护内部state,直接使用父组件传入的value和onChangeText即可

父组件(Login类组件)修改

// imports
import EmailInput from '../components/EmailInput';
import React, { Component } from 'react';

class Login extends Component { 
  state = {
    inputValue: '',
  }

  // 直接接收回调返回的输入文本即可
  onChangeText = (text) => {
    this.setState({inputValue: text});
  };

  render() {
    return (
      <EmailInput 
        value={this.state.inputValue} 
        onChangeText={this.onChangeText} 
      />
    )
  }
};

子组件(EmailInput函数组件)修改

import React from 'react';
import { TextInput, StyleSheet } from 'react-native';

// 入参是props对象,需要解构属性必须加{}包裹
const EmailInput = ({ onChangeText, value }) => {
  return ( 
    <TextInput 
      autoCapitalize='none'
      value={value} 
      onChangeText={onChangeText} 
      style={styles.userTextInput} 
    />
  )
}

const styles = StyleSheet.create({
  userTextInput: {
    // 自定义输入框样式
  }
})

export default EmailInput;

调整完成后父组件state.inputValue就是TextInput的实时输入值,你最初的InputName组件如果需要实现同样能力,按上述逻辑传参绑定即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 14:54:03