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ân | Ví 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
- Luôn bọc text trong <Text> - Không bao giờ để text "trôi" trong View.
- 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. - Format code nhất quán - Tránh copy-paste từ web/blog mang theo ký tự lạ.
- Conditional rendering an toàn:
{show &&Content } // Đúng {show && 'Content'} // Sai - gây lỗi - Fragment cho nhiều Text:
<>
Line 1 Line 2 > // Hoặc (nested Text hợp lệ)Line 1 Line 2
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.