Reputation: 611
I want to render local state in LiestView. I'm not familiar with ListView,¥. it didn't work.
export default class Top extends Component {
state=[{title: 'a'}, {title: 'b'}, {title: 'c'}]
_renderItem = ({item}) => (
<View>
<Text>{item.key}</Text> // here
<Category />
</View>
);
render() {
return (
<FlatList
data={this.state.data}
renderItem={this._renderItem(item)}
/>
);
}
}
below is my code. it workes. How to change this code? I need title.
export default class Top extends Component {
state={
data:[{}, {}, {}]
};
_renderItem = () => (
<View>
<Category />
</View>
);
render() {
return (
<FlatList
data={this.state.data}
renderItem={this._renderItem}
/>
);
}
}
thanks for your time.
Upvotes: 0
Views: 1320
Reputation: 7309
First Import ListView
import {View, Text, ListView} from 'react-native';
in your component will mount create data source like this
componentWillMount(){
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.dataSource = ds.cloneWithRows(this.props.yourProps);
}
render the list view
render() {
return (
<View>
<ListView
enableEmptySections
dataSource = {this.dataSource}
renderRow={this.renderRow}
/>
</View>
);
}
finally you have to let the ListView know which data and how you want to show the data in the list view. For this create a function that renders the rows of the list View
renderRow(yourProps) {
return (
<Text>{yourProps.yourData}</Text>
);
}
You can style the row whatever way you want.
For more you can check this repo in gitHub: https://github.com/ishraqe/manage-user/blob/master/src/components/EmployeeList.js
Upvotes: 0
Reputation: 677
The state must be an object and if you don't have a key prop, then you need to define a keyExtractor:
import React, { Component } from "react";
import { Text, View, FlatList } from "react-native";
export default class Top extends Component {
state = {
data: [{ id: 1, title: "a" }, { id: 2, title: "b" }, { id: 3, title: "c" }]
};
_renderItem = ({ item }) => (
<View>
<Text>{item.title}</Text>
</View>
);
// You could use the title instead of the id, but not very scalable
_keyExtractor = (item, index) => item.id;
render() {
return (
<FlatList
data={this.state.data}
renderItem={this._renderItem}
keyExtractor={this._keyExtractor}
/>
);
}
}
Upvotes: 1