First on the renderings:
It's a list like this. UICollectionView can write this type of list directly in iOS, but it can be done directly with FlatList in react native. That is to say, this type of list is no different from ordinary list, just a little different in layout. Let's do it!
1. Render a list
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => index}
contentContainerStyle={styles.list_container}
/>
</View>
)
};
2. Give the list a style
list_container: {
// Spindle direction
flexDirection:'row',
justifyContent: 'space-between',
// One line cannot be displayed, change to another
flexWrap:'wrap',
// Lateral axis direction
alignItems:'center', // Must be set, or line feed will not work
paddingHorizontal: 20,
},
Note here: the three properties of flexdirection flexwrap alignitems must be set
In fact, the most important thing to write the nine palace grid list is this one
Full code:
const {width, height} = Dimensions.get('window')
const cols = 2;
const vMargin = 20;
const cellWH = (width-2*vMargin-15)/cols;
const hMargin = 25;
export default class AllRecommend extends Component {
constructor(props) {
super(props)
this.state = {
data: [],
}
};
componentDidMount() {
this.fetchData();
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => index}
contentContainerStyle={styles.list_container}
/>
</View>
)
};
renderItem({item, index}) {
return (
<TouchableOpacity activeOpacity={0.5}>
<View style={styles.item}>
<Image source={{uri: item['image']}} style={{width: cellWH,height:cellWH, borderRadius: 5}}/>
<Text style={{marginTop: 5, textAlign: 'center'}} numberOfLines={1}>{item.title}</Text>
</View>
</TouchableOpacity>
)
}
fetchData() {
NetRequest.get('https://API. Doublan. COM / V2 / music / search? Q = Li Zhi ',null,null).then((response) => {
this.setState({
data: response['musics']
})
}, (error) => {
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: color.white,
paddingVertical: 15,
},
list_container: {
// Spindle direction
flexDirection:'row',
justifyContent: 'space-between',
// One line cannot be displayed, change to another
flexWrap:'wrap',
// Lateral axis direction
alignItems:'center', // Must be set, or line feed will not work
paddingHorizontal: 20,
},
item: {
width:cellWH,
marginTop:hMargin,
alignItems: 'center',
}
})
The size of each item can be set according to its actual needs
enjoy it!
Xiaobai development exchange group: 860196537