【问题标题】:React Native TextInput save to constReact Native TextInput 保存到 const
【发布时间】:2019-08-07 13:15:41
【问题描述】:

总结

我有一个反应原生功能组件,我在 TextInput 中从用户那里收集一个值,然后需要在按下按钮时将该值传递给一个函数。我知道如何在带有状态的本机类组件中执行此操作,但是我正在尝试使用功能组件。

我快要搞清楚了,但我只是错过了一些东西。我到目前为止的代码如下。

saveUserInput 句柄保存来自用户的文本并返回输入。当我将 saveUserInput 传递给 forgotPassword(我的函数将 userInput 发送到我的后端以重置密码)时,saveUserInput 被定义为函数,而不是它返回的值。如何使它作为功能组件工作?

代码

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>
  );
});

【问题讨论】:

  • 可以在功能组件中使用state
  • 带挂钩?是否可以在不使用钩子的情况下做到这一点?
  • 是的,带钩子。还有其他方法,但它们都有缺点

标签: javascript reactjs react-native


【解决方案1】:
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>
  );
});

这应该可以在不使用钩子的情况下解决问题。拉出输入变量以供所有其他组件使用。 但是使用 useState 挂钩可能会更轻松。

【讨论】:

  • 我最终使用了钩子,你说得对,它更容易!谢谢你的回答,我很感激!
猜你喜欢
  • 2019-08-12
  • 2020-11-15
  • 2023-02-25
  • 2016-04-11
  • 2017-12-28
  • 2021-02-02
  • 1970-01-01
  • 2018-09-11
  • 2020-04-02
相关资源
最近更新 更多