我正在尝试在React Native中实现Listview。我遵循了官方文档,但没有成功。基本上我从数据库中获得有关演员姓名及其各自姓氏的响应,如下所示
[
{"Name":"Amitabh","LastName":"Bachchan"},
{"Name":"Jaya","LastName":"Bhaduri Bachchan"},
{"Name":"Hrithik","LastName":"Roshan"},
{"Name":"Shahrukh","LastName":"Khan"},
{"Name":"Akshay","LastName":"Kumar"},
]
到目前为止,这是我的代码
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource:ds.cloneWithRows(['row 1', 'row 2']),
};
}
componentDidMount() {
//this is where i get data from previous screen as i mentioned in above format then i pass to state
this.setState({
dataSource: this.props.source,
})
}
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<View
style={styles.CanContainer}>
<View
style={styles.CanSubContainer}>
<View style={{flex: 1, alignItems: 'center'}}>
<Text style={styles.canTitles}>
{rowData.Name}
</Text>
</View>
<View style={{flex: 1, alignItems: 'center'}}>
<Text style={styles.canTitles}>
{rowData.LastName}
</Text>
</View>
</View>
</View>
}
/>
答案 0 :(得分:0)
您不能将数据直接分配给listview数据源。更改构造函数,并将listview数据源移动到全局状态。另外,您不能将JSON分配给listview数据源。您必须将JSON响应转换为javascript对象/数组。您可以为此使用JSON.parse()函数。
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
export default class Example extends Component {
constructor(props) {
super(props)
const myData = JSON.parse(props.source);
this.state = {
dataSource: ds.cloneWithRows(myData),
}
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<View
style={styles.CanContainer}>
<View
style={styles.CanSubContainer}>
<View style={{ flex: 1, alignItems: 'center' }}>
<Text style={styles.canTitles}>
{rowData.Name}
</Text>
</View>
<View style={{ flex: 1, alignItems: 'center' }}>
<Text style={styles.canTitles}>
{rowData.LastName}
</Text>
</View>
</View>
</View>
}
/>
);
}
}