反应本机:意外的文本节点:。文本节点不能是<View>



我正在制作一个React Native应用程序,我得到错误:

意外文本节点:。文本节点不能是的子节点。

我不知道这个错误指的是哪个文本节点。我的目标是渲染一个视图数组。

下面是重现错误的最小代码片段:

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

function fun() {
const views = [];
const style = {backgroundColor: 'red', height: 100, width: 100};
for (let i=0; i<3; i++) {
views.push(
<View key={i} style={style}/>
)
}
return views;
}
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>

<View> {fun()} </View>

</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

问题是,一个函数应该是一个JSX组件,或者在这种情况下返回一个JSX组件,必须是一个JSX元素,而不是一个JSX元素数组。

因此,您需要添加一个顶层组件,它可能只是一个片段。

function fun() {
const views = []
const style = { backgroundColor: "red", height: 100, width: 100 }
for (let index = 0; index < 3; index++) {
views.push(<View key={index} style={style} />)
}
return <>{views}</>
}

您正在返回一个视图数组。必须将视图作为子视图返回。试试这样写:

function fun() {
const style = { backgroundColor: "red", height: 100, width: 100 };
return [0, 1, 2].map(() => <View key={i} style={style} />);
}
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<View> {fun()} </View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

查看React Native文档https://reactnative.dev/docs/0.65/text

不能将文本节点直接放在<View>下。

<View>
<MyAppText>
Text styled with the default font for the entire application
</MyAppText>
<MyAppHeaderText>Text styled as a header</MyAppHeaderText>
</View>

实际上我解决了我的.....这给我错误,因为视图和文本之间的空间
,所以我删除视图和文本之间的所有空间。错误了

最新更新