简体   繁体   English

React Native TextInput保存到const

[英]React Native TextInput save to const

Summary 摘要

I have a react native functional component where I collect a value from the user in TextInput and then need to pass that value to a function when a button is pressed. 我有一个react native函数组件,该组件在TextInput中从用户那里收集值,然后在按下按钮时将该值传递给函数。 I know how to do this in a react native class component with state, however I'm trying to use a functional component. 我知道如何在带有状态的React Native类组件中执行此操作,但是我正在尝试使用功能组件。

I'm close to figuring it out but I'm just missing something. 我快要弄清楚了,但我只是想念一些东西。 The code I have so far is below. 我到目前为止的代码如下。

saveUserInput handles saves the text from the user and returns input. saveUserInput句柄保存用户的文本并返回输入。 When I pass saveUserInput into forgotPassword, which is my function that sends userInput to my backend to reset password, saveUserInput is defined as the function as opposed to the value it returns. 当我将saveUserInput传递到forgotPassword时,这是我将userInput发送到后端以重置密码的函数,将saveUserInput定义为该函数,而不是返回的值。 How can make this work as a functional component? 如何使它作为功能组件起作用?

Code

export default (ForgotPasswordScreen = () => {

  const saveUserInput = userInput => {
    const input = userInput;
    return input;
  };

  return (
    <View style={styles.container}>
      <Text style={styles.headerText}>Forgot Password</Text>
      <Text style={styles.forgotText}>
        Enter your username or email address below to reset your password
      </Text>
      <TextInput
        onChangeText={userInput => saveUserInput(userInput)}
        placeHolder={"username or email"}
      />
      <Text
        style={styles.buttonText}
        onPress={saveUserInput => forgotPassword(saveUserInput)}
      >
        Forgot Password Button
      </Text>
    </View>
  );
});
export default (ForgotPasswordScreen = () => {
  let input = '';
  const saveUserInput = userInput => {
    input = userInput;
  };

  return (
    <View style={styles.container}>
      <Text style={styles.headerText}>Forgot Password</Text>
      <Text style={styles.forgotText}>
        Enter your username or email address below to reset your password
      </Text>
      <TextInput
        onChangeText={userInput => saveUserInput(userInput)}
        placeHolder={"username or email"}
      />
      <Text
        style={styles.buttonText}
        onPress={() => forgotPassword(input)}
      >
        Forgot Password Button
      </Text>
    </View>
  );
});

This should do the trick without using hooks. 这应该在不使用钩子的情况下完成。 Pull out the input variable to be in scope for all other components to use. 拉出输入变量,以使其包含在所有其他组件中。 But life could be much easier using useState hooks. 但是使用useState挂钩可以使生活更加轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM