component" ใน React Native สาเหตุหลักคือ indentation และ trailing spaces">
 Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แก้ไขข้อผิดพลาด "Text strings must be rendered within a <Text> component" ใน React Native


ขณะพัฒนาแอป อาจเจอข้อผิดพลาดดังกล่าว โค้ดที่ทำให้เกิดข้อผิดพลาด:

ตัวอย่างที่ทำให้เกิด Error

import React from "react";
import { Image, Text, View, StyleSheet } from "react-native";

export default class App extends React.Component {
  render() {
    return (
      
        
      
    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 50,
    paddingLeft: 50,
  },
  stretch: {
    width: 200,
    height: 200,
    resizeMode: 'stretch',
  },
});

ข้อผิดพลาดที่แสดง

แก้ไขข้อผิดพลาด  Text strings must be rendered within a <Text> component  ใน React Native

สาเหตุของข้อผิดพลาด

  1. Indentation (การเยื้อง) ไม่ถูกต้อง - จำเป็นต้องเยื้องคอมโพเนนต์ลูกให้ถูกต้องภายในคอมโพเนนต์ผู้ปกครอง
  2. เว้นวรรค (spaces) ค้างอยู่ท้ายคอมโพเนนต์ - ลบเว้นวรรคท้ายบรรทัดแล้วคอมไพล์ใหม่ จะทำงานได้ปกติ ระวังเมื่อ copy-paste โค้ดจากแหล่งอื่น

โค้ดที่แก้ไขแล้ว

import React from "react";
import { Image, Text, View, StyleSheet } from "react-native";

export default class App extends React.Component {
  render() {
    return (
      
        
      
    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 50,
    paddingLeft: 50,
  },
  stretch: {
    width: 200,
    height: 200,
    resizeMode: 'stretch',
  },
});

ผลลัพธ์หลังแก้ไข

แก้ไขข้อผิดพลาด  Text strings must be rendered within a <Text> component  ใน React Native

สรุปวิธีป้องกัน

  • ใช้ code formatter (Prettier) เพื่อจัดรูปแบบอัตโนมัติ
  • ตรวจสอบ whitespace ท้ายบรรทัด (trailing spaces)
  • ระวังการ copy-paste โค้ดจากเว็บไซต์หรือ PDF
  • ใช้ IDE ที่แสดง invisible characters