最近在使用React Native FlatList
时遇到了麻烦。我要做的就是使用FlatList
显示日历块。这是我的代码
Calendar.js
:
import {View , Text, StyleSheet, FlatList} from 'react-native'
import React from 'react'
import {DayItem} from './DayItem'
export const Calendar = () => {
const DayList = Array.of(42);
for(i=0;i<42;i++){
DayList[i] = i;
}
const element = DayList.map(item => (<DayItem number = {item}></DayItem>) )
return(
<View style = {{flex:3, borderStyle: 'solid' , borderTopWidth:0.5,
borderBottomWidth:0.5, alignItems:'center'}}>
<View style = {{flex:1,borderStyle: 'solid', borderColor: 'blue', borderWidth : 1,
marginTop:5, marginBottom:2, width:370, alignItems:'stretch'}}>
<View style = {{ flex:1, borderStyle: 'solid', borderBottomWidth: 1,
flexDirection:'row', borderBottomColor: 'red', justifyContent: 'space-between',
marginTop:3}}>
<Text style = {style.textWeek}>Mon</Text>
<Text style = {style.textWeek}>Tue</Text>
<Text style = {style.textWeek}>Wed</Text>
<Text style = {style.textWeek}>Thu</Text>
<Text style = {style.textWeek}>Fri</Text>
<Text style = {style.textWeek}>Sat</Text>
<Text style = {style.textWeek}>Sun</Text>
</View>
<View style = {{flex:14, borderStyle: 'solid', borderWidth: 1, borderColor: 'yellow',
}}>
<FlatList data = {element} renderItem = {renderDayItem} keyExtractor = {keyExtract}
numColumns ={numColumns} />
</View>
</View>
</View>
)
}
const numColumns = 7
const renderDayItem = ({item})=> (
<DayItem number = {item}></DayItem>
)
const keyExtract = (item) => item
const style = StyleSheet.create({
textWeek :{
color : 'blue',
fontSize : 11,
flex:1,
textAlign: 'center'
}
})
还有DayItem.js
,其中显示了一个视图和嵌套在其中的文本:
import React from 'react'
import {View, StyleSheet,Text } from 'react-native'
export const DayItem = ({number})=>{
return(
<View style = {{borderStyle:'solid', borderColor:'black', borderWidth:1,
backgroundColor:'yellow', height:40, width:50,
marginTop:2, marginLeft:2, marginRight:2, marginBottom:2}}>
<Text>{number}</Text>
</View>
)
}
运行代码时,我发现此错误:
永久违反:当前不支持在文本中嵌套视图。
但是当我将Calendar.js
中的代码更改为此时:
<View style = {{flex:14, borderStyle: 'solid', borderWidth: 1, borderColor: 'yellow',
}}>
{element}
</View>
代码运行得很好。当我在<Text/>
的{{1}}内删除<View/>
元素并继续使用DayItem.js
时,代码也运行良好,并且呈现得非常好。我想知道React Native是否不支持在FlatList
的{{1}}内嵌套Text
。真的吗?如果是这样,那么谁能告诉我如何用另一种方式渲染View
块。我希望它们看起来像使用FlatList
一样。
我的React Native版本也是0.59.8
答案 0 :(得分:1)
问题是您在DayItem
中以number
的身份renderDayItem
传递
const element = DayList.map(item => (<DayItem number = {item}></DayItem>) )
<FlatList data = {element} renderItem = {renderDayItem} keyExtractor = {keyExtract}
const renderDayItem = ({item})=> (
<DayItem number = {item}></DayItem>
)
因此您的DayItem
代码类似于
<View style = {{borderStyle:'solid', borderColor:'black', borderWidth:1,
backgroundColor:'yellow', height:40, width:50,
marginTop:2, marginLeft:2, marginRight:2, marginBottom:2}}>
<Text><DayItem ...></Text>
</View>
我认为您想将DayList
作为数据而不是DayItem
的列表传递
<FlatList data = {DayList} renderItem = {renderDayItem} keyExtractor = {keyExtract}