这是我的示例代码,我希望ListView
在点击时更新元素。
此行定义样式:
(this.state.selectedField.id==field.id)?'green':'white'
在此示例中,活动View
应以绿色突出显示。内部状态正在更新handleClick()
,但renderField()
没有调用方法。
如何使 ListView 在单击触发的状态更改时重新呈现?
import React, {Component} from 'react';
import {
AppRegistry,
View,
ListView,
Text,
TouchableOpacity
} from 'react-native';
class SampleApp extends Component {
constructor(props) {
super(props);
var ds = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
});
this.state = {
fields: ds.cloneWithRows([
{id:0},{id:1},{id:2}
]),
selectedField: {id:0}
};
}
handleClick(field) {
console.log("Selected field:",field);
this.setState({
selectedField: field
});
}
renderField(field) {
return (
<TouchableOpacity onPress={this.handleClick.bind(this, field)} >
<View style={{backgroundColor:(this.state.selectedField.id==field.id)?'green':'white'}}>
<Text style={{left:0, right:0, paddingVertical:50,borderWidth:1}}>{field.id}</Text>
</View>
</TouchableOpacity>
);
}
render() {
return (
<View>
<ListView
dataSource={this.state.fields}
renderRow={this.renderField.bind(this)}
/>
</View>
);
}
}
AppRegistry.registerComponent('SampleApp', () => SampleApp);