【问题标题】:React: How Do I get the value of a custom TextInput Component?React:如何获取自定义 TextInput 组件的值?
【发布时间】:2021-01-15 22:05:43
【问题描述】:

我有自定义 TextInput 组件的代码,我想将此组件用于登录屏幕的用户名和密码值,但是,我不知道如何检索特定实例的文本输入值.

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

const TextInputCustom = (props) => {
  const [value, onChangeText] = React.useState();

  return (
    <View style={styles.container}>
    <TextInput
      placeholder={props.name}
      style={styles.textInput}
      onChangeText={text => onChangeText(text)}
      value={value}
    />
    </View>
  );
}

导入后我在登录屏幕中创建

<TextInputCustom name="Username"/>
<TextInputCustom name="Password"/>

如何获取该值以便可以将其分配给每个 TextInputCustom 实例的变量?

【问题讨论】:

  • 您是否有权访问该组件的 API?那将是一个开始寻找的好地方。通常,您有 onChange 处理程序。我还看到你有onChangeText 作为道具,但由于你仍然面临问题,我假设它不起作用。所以尝试检查 API 并使用正确的道具
  • 你试过使用回调函数吗?

标签: javascript reactjs react-native


【解决方案1】:

您需要将valueonChange 移至父级:

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

const TextInputCustom = (props) => {
  const {value, onChange} = props;

  return (
    <View style={styles.container}>
    <TextInput
      placeholder={props.name}
      style={styles.textInput}
      onChangeText={text => onChange(text)}
      value={value}
    />
    </View>
  );
}

然后像这样使用它:

<TextInputCustom name="Username" value={username} onChange={onUsernameChange} />
<TextInputCustom name="Password" value={password} onChange={onPasswordChange} />

这是通常用于简单组件的做法。您不需要在组件级别处理值,而是在使用您的自定义组件的组件中处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-05
    • 2021-08-17
    • 2022-12-11
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    相关资源
    最近更新 更多