如何在React Native中从RoundedTextField获取登录屏幕上的输入文本

mdfafbf1  于 2023-05-07  发布在  React
关注(0)|答案(1)|浏览(125)
export default function LoginScreen() {
  return (
    <Screen>
      <View style={styles.containerView}>
        <Text style={styles.headerText}>LOGIN</Text>
        <Image
          style={styles.logoStyle}
          source={require("../assets/logo.png")}
        />
        <RoundedTextField placeholder={"Mobile Number"} />
        <Text>{**"Wants RoundedTextField's Text Here"**}</Text>
      </View>
    </Screen>
  );
}

export default function RoundedTextField({ placeholder }) {
  const [text, setText] = useState("");

  return (
    <TextInput
      style={styles.textInput}
      placeholder={placeholder}
      onChangeText={(newText) => setText(newText)}
      defaultValue={text}
    />
  );
}
j13ufse2

j13ufse21#

您可以从父LoginScreen组件向RoundedTextField组件传递一个回调函数,该函数将使用在RoundedTextField中输入的值更新LoginScreen的状态。

export default function LoginScreen() {
  const [mobileNumber, setMobileNumber] = useState("");

  const handleMobileNumberChange = (newMobileNumber) => {
    setMobileNumber(newMobileNumber);
  };

  return (
    <Screen>
      <View style={styles.containerView}>
        <Text style={styles.headerText}>LOGIN</Text>
        <Image style={styles.logoStyle} source={require("../assets/logo.png")} />
        <RoundedTextField
          placeholder={"Mobile Number"}
          onTextChange={handleMobileNumberChange}
        />
        <Text>{mobileNumber}</Text>
      </View>
    </Screen>
  );
}

export default function RoundedTextField({ placeholder, onTextChange }) {
  const [text, setText] = useState("");

  const handleTextChange = (newText) => {
    setText(newText);
    onTextChange(newText); // invoke callback function to update state in parent component
  };

  return (
    <TextInput
      style={styles.textInput}
      placeholder={placeholder}
      onChangeText={handleTextChange}
      value={text} // use "value" instead of "defaultValue" to set the initial value
    />
  );
}

相关问题