Ошибка ввода собственного текста React: текстовые строки должны отображаться в компоненте

#javascript #react-native

Вопрос:

Я новичок в React Native и пытаюсь создать страницу регистрации в своем приложении.

Эта страница работает в браузере Chrome, она подключается к экспресс-серверу и отправляет данные в MongoDB, хотя она выдает предупреждения в консоли Chrome: index.js:1 Unexpected text node: A text node cannot be a child of a lt;Viewgt;. , эта ошибка возникает каждый раз, когда я использую @ при вводе электронной почты, она также случайным образом возникает, когда я использую некоторые другие символы при вводе имени пользователя и пароля.

Но когда я делаю то же самое на своем телефоне с помощью Expo Go, то есть, когда я ввожу @ или другие виды ввода в трех текстовых вводах, это приложение выходит из строя напрямую…, появляется сообщение об ошибке Error: Text strings must be rendered within a lt;Textgt; component. .

Я не уверен, какая часть этой страницы вызывает такую ошибку, потому что я использую текстовые компоненты для переноса их содержимого.

Мой код таков:

 import React, { useState } from "react"; import { Button, StyleSheet, Text, TextInput, View } from "react-native"; import { useValue } from "./ValueContext"; import Axios from "axios";   const RegisterScreen = ({ navigation, route }) =gt; {   const { currentValue, setCurrentValue } = useValue()  const [name, setName] = useState("");  const [email, setEmail] = useState("");  const [password, setPassword] = useState("");  const [result, setResult] = useState(0);   const validateEmail = (value) =gt; {  if (value !== "") {  let re = /@ /  let cond = re.test(value)  if (!cond) {  return (lt;Viewgt;  lt;Text style={{ color: "red" }}gt;Email should contain @ lt;/Textgt;  lt;/Viewgt;)  } else {  return (lt;Viewgt; lt;/Viewgt;)  }  } else {  return (lt;Viewgt;  lt;Text style={{ color: "red" }}gt;Email is required lt;/Textgt;  lt;/Viewgt;);  }  }   const validateName = (value) =gt; {  if (value !== "") {  let c = value[0].toLowerCase();  let cond = "a" lt;= c amp;amp; c lt;= "z"  if (!cond) {  return (lt;Viewgt;  lt;Text style={{ color: "red" }}gt;Username can only start with a character lt;/Textgt;  lt;/Viewgt;);  } else {  return (lt;Viewgt;lt;/Viewgt;);  }  } else {  return (lt;Viewgt;  lt;Text style={{ color: "red" }}gt;UserName is required lt;/Textgt;  lt;/Viewgt;);  }  }  const validatePassword = (value) =gt; {  if (value !== "") {  let re1 = /[a-zA-Z] /  let re2 = /[0-9] /  let re3 = /[!@#$%^amp;*] /  let cond = re1.test(value) amp;amp; re2.test(value) amp;amp; re3.test(value)  if (!cond) {  return (lt;Viewgt;  lt;Text style={{ color: "red" }}gt;Password should contain at least one character, one number and one special characterlt;/Textgt;  lt;/Viewgt;);  } else {  return (lt;Viewgt;lt;/Viewgt;)  }  } else {  return (lt;Viewgt;  lt;Text style={{ color: "red" }}gt;Password is required lt;/Textgt;  lt;/Viewgt;);  }  }   const displayResult = (value) =gt; {  if (value === 0) {  return (lt;Viewgt;lt;/Viewgt;)  } else if (value === 1) {  return (lt;Viewgt;  lt;Text style={{ color: "red" }}gt; Registration is successful! Please Loginlt;/Textgt;  lt;Button  title="Login In"  onPress={() =gt; navigation.navigate('Login', { version: "CPA 5.0" })}  /gt;  lt;/Viewgt;)  } else if (result === 2) {  return (lt;Viewgt;  lt;Text style={{ color: "red" }}gt;Registration failed, this email has ready linked to one account, please go to loginlt;/Textgt;  lt;Button  title="Login In"  onPress={() =gt; navigation.navigate('Login', { version: "CPA 5.0" })}  /gt;  lt;/Viewgt;)  }  }   const userRegistration = async () =gt; {  try {  let serverURL = currentValue.serverURL;   const registerStatus = await Axios({  method: "post",  url: "/register",  baseURL: serverURL,  data: { userEmail: email, userName: name, userPassword: password },  });  if (registerStatus.data["status"] === true) {  // console.log("case1")  setResult(1)  } else {  // console.log('case2')  setResult(2)  }  } catch (error) {  console.log(error);  }  }   return (  lt;View style={styles.container}gt;  lt;View style={{ alignItems: "center" }}gt;  lt;Text style={{ fontSize: 20, textAlign: "center" }}gt;Unit Converter version lt;Text style={{ color: "red" }}gt;{route.params.version}lt;/Textgt;lt;/Textgt;  lt;/Viewgt;   lt;Viewgt;  lt;Text style={{ fontSize: 20, textAlign: "center" }}gt;Register an account herelt;/Textgt;  lt;/Viewgt;   lt;View style={{ flexDirection: "row", justifyContent: "center" }}gt;  lt;Text style={{ fontSize: 15 }}gt;Enter Your Email lt;/Textgt;  lt;TextInput  placeholder="Enter your email"  onChangeText={(email) =gt; { setEmail(email) }}  value={email}  style={{ fontSize: 15 }}  /gt;  lt;/Viewgt;   {validateEmail(email)}   lt;View style={{ flexDirection: "row", justifyContent: "center" }}gt;  lt;Text style={{ fontSize: 15 }}gt;Enter Your Name lt;/Textgt;  lt;TextInput  placeholder="Enter your name"  onChangeText={(name) =gt; { setName(name) }}  value={name}  style={{ fontSize: 15 }}  /gt;  lt;/Viewgt;   {validateName(name)}   lt;View style={{ flexDirection: "row", justifyContent: "center" }}gt;  lt;Text style={{ fontSize: 15 }}gt;Enter Your Password lt;/Textgt;  lt;TextInput  placeholder="Enter your password"  onChangeText={(password) =gt; { setPassword(password) }}  value={password}  style={{ fontSize: 15 }}  secureTextEntry={true}  /gt;  lt;/Viewgt;   {validatePassword(password)}  lt;Button  title="Register"  onPress={() =gt; {  userRegistration();  }}  /gt;  {displayResult(result)}    lt;/Viewgt;  ); } const styles = StyleSheet.create({  container: {  flex: 1,  flexDirection: 'column',  alignItems: "center",  justifyContent: 'flex-start',  backgroundColor: "grey",  }, });  export default RegisterScreen;   

Сообщения об ошибках, упомянутые выше, являются:

 Error: Text strings must be rendered within a lt;Textgt; component.  This error is located at:  in RCTView (at View.js:34)  in View (at register.js:33)  in RCTView (at View.js:34)  in View (at register.js:111)  in RegisterScreen (at SceneView.tsx:126)  in StaticContainer  in StaticContainer (at SceneView.tsx:119)  in EnsureSingleNavigator (at SceneView.tsx:118)  in SceneView (at useDescriptors.tsx:209)  in RCTView (at View.js:34)  in View (at DebugContainer.native.tsx:27)  in DebugContainer (at NativeStackView.native.tsx:71)  in MaybeNestedStack (at NativeStackView.native.tsx:229)  in RNSScreen (at createAnimatedComponent.js:165)  in AnimatedComponent (at createAnimatedComponent.js:215)  in ForwardRef(AnimatedComponentWrapper) (at src/index.native.tsx:147)   in Screen (at NativeStackView.native.tsx:175)  in SceneView (at NativeStackView.native.tsx:277)  in RNSScreenStack (at NativeStackView.native.tsx:268)  in NativeStackViewInner (at NativeStackView.native.tsx:322)  in RNCSafeAreaProvider (at SafeAreaContext.tsx:76)  in SafeAreaProvider (at SafeAreaProviderCompat.tsx:46)  in SafeAreaProviderCompat (at NativeStackView.native.tsx:321)  in NativeStackView (at createNativeStackNavigator.tsx:67)  in NativeStackNavigator (at App.js:33)  in EnsureSingleNavigator (at BaseNavigationContainer.tsx:430)  in ForwardRef(BaseNavigationContainer) (at NavigationContainer.tsx:132)  in ThemeProvider (at NavigationContainer.tsx:131)  in ForwardRef(NavigationContainerInner) (at App.js:32)  in ValueProvider (at App.js:31)  in App (created by ExpoRoot)  in ExpoRoot (at renderApplication.js:45)  in RCTView (at View.js:34)  in View (at AppContainer.js:106)  in DevAppContainer (at AppContainer.js:121)  in RCTView (at View.js:34)  in View (at AppContainer.js:132)  in AppContainer (at renderApplication.js:39)  

и

 index.js:1 Unexpected text node: . A text node cannot be a child of a lt;Viewgt;. console.lt;computedgt; @ index.js:1 error @ react-native-logs.fx.ts:34 (anonymous) @ index.js:94 (anonymous) @ index.js:92 renderWithHooks @ react-dom.development.js:14803 updateForwardRef @ react-dom.development.js:16816 beginWork @ react-dom.development.js:18645 beginWork$1 @ react-dom.development.js:23179 performUnitOfWork @ react-dom.development.js:22157 workLoopSync @ react-dom.development.js:22130 performSyncWorkOnRoot @ react-dom.development.js:21756 (anonymous) @ react-dom.development.js:11089 unstable_runWithPriority @ scheduler.development.js:653 runWithPriority$1 @ react-dom.development.js:11039 flushSyncCallbackQueueImpl @ react-dom.development.js:11084 flushSyncCallbackQueue @ react-dom.development.js:11072 flushPendingDiscreteUpdates @ react-dom.development.js:21847 flushDiscreteUpdates @ react-dom.development.js:21827 finishEventHandler @ react-dom.development.js:764 batchedEventUpdates @ react-dom.development.js:798 dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568 attemptToDispatchEvent @ react-dom.development.js:4267 dispatchEvent @ react-dom.development.js:4189 unstable_runWithPriority @ scheduler.development.js:653 runWithPriority$1 @ react-dom.development.js:11039 discreteUpdates$1 @ react-dom.development.js:21887 discreteUpdates @ react-dom.development.js:806 dispatchDiscreteEvent @ react-dom.development.js:4168  

Комментарии:

1. Какая именно строка вызывает ошибку?

Ответ №1:

введите описание изображения здесь
Вы пытаетесь вставить текст сюда динамически.На самом деле это работает в вашем браузере, так как ваш браузер очень хорошо понимает HTML, но ваш мобильный телефон не работает, поэтому в react native каждый текстовый компонент должен быть завернут в компонент

 lt;Textgt;{Validate()}lt;/Textgt;