component" trong React Native: text node lẻ, khoảng trắng, conditional rendering.">
 Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xử lý lỗi "Text strings must be rendered within a component" trong React Native


Lỗi "Text strings must be rendered within a <Text> component" là lỗi phổ biến khi mới học React Native. Nguyên nhân: **Văn bản thuần túy (text node) nằm trực tiếp trong View hoặc component container khác**, không được bọc bằng <Text>.

Ví dụ gây lỗi

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

export default class App extends React.Component {
  render() {
    return (
      
        
        {' '}  {/* <-- Dấu cách/thành text node lẻ này gây lỗi! */}
      
    );
  }
}

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

Các nguyên nhân phổ biến

Nguyên nhânVí dụSửa thế nào
Khoảng trắng/dòng mới giữa các component trong JSX <View>\n <Text>A</Text>\n <Text>B</Text>\n</View> Xóa khoảng trắng/dòng mới thừa, hoặc bọc text trong <Text>.
Text node lẻ ngoài <Text> <View>Hello</View> <View><Text>Hello</Text></View>
Biến string render trực tiếp không bọc Text <View>{myString}</View> <View><Text>{myString}</Text></View>
Copy-paste code mang theo ký tự ẩn (zero-width space, BOM) Không thấy bằng mắt thường Xóa và gõ lại, hoặc dùng editor show invisible characters.
Conditional rendering trả về string thay vì component {condition && 'Some text'} {condition && <Text>Some text</Text>}

Code đã sửa (Ví dụ trên)

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

export default class App extends React.Component {
  render() {
    return (
      
        
        {/* Xóa khoảng trắng lẻ ở đây */}
      
    );
  }
}

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

Best Practices tránh lỗi này

  1. Luôn bọc text trong <Text> - Không bao giờ để text "trôi" trong View.
  2. Dùng ESLint + Prettier - Cấu hình rule react-native/no-raw-text (từ eslint-plugin-react-native) sẽ báo lỗi ngay khi code.
  3. Format code nhất quán - Tránh copy-paste từ web/blog mang theo ký tự lạ.
  4. Conditional rendering an toàn:
    {show && Content}  // Đúng
    {show && 'Content'}  // Sai - gây lỗi
  5. Fragment cho nhiều Text:
    <>
      Line 1
      Line 2
      // Hoặc Line 1Line 2 (nested Text hợp lệ)

Debug nhanh

Nếu lỗi không rõ dòng nào: Comment từng phần JSX cho đến khi lỗi biến mất -> tìm ra vị trí chính xác.