ReactNative 用ListView实现GridView效果
直接上代码,多说无用. 先构造数据;
//构造数据
request() {
const rowData = Array.from(new Array(15))
.map((value, index) => ({text: "item " + index, clicked: 0}))
.concat(this.state.listData);
this.setState({
isRefresh: false,
listData: rowData,
});
}
根据实际情况封装你的GridView,这里简单展示实现的关键点
//关键点是定义flexDirection:"row",flexWrap:"wrap"这两个属性.
GridView = (column,margin) => {
return <ListView
//显示竖直滚动条
showsVerticalScrollIndicator = { true }
//定义content的样式,这里是 contentContainerStyle,而不是style
contentContainerStyle={{
width: Dimensions.get("window").width,
backgroundColor: "#ffffff",
flexDirection: "row",
flexWrap: "wrap",
alignItems:"center" }}
//数据源
dataSource={this.state.dataSource.cloneWithRows(this.state.listData)}
//渲染Item
renderRow={(rowData, index) => {
let w = ( Dimensions.get("window").width - column * margin * 2 )
/ column;
//这里是自已定义的ItemView
return <CButton key={index} style={{width: w, height: 50,
borderRadius: 5, margin: margin}} onPress={() => {
ToastAndroid.show(rowData.text, ToastAndroid.SHORT)
}} text={rowData.text}/>
}}
/>
}
然后在render数中调用这个方法即可
render(){
<View>
... ...
{this.GridView(3,5)}
... ...
</View>
}