我正在运行一个示例项目。在我的项目中,我使用的是 listView。如果我单击向上箭头按钮,值将增加,单击向下箭头按钮,值将减少。当我单击这两个按钮中的任何一个时,listView 中所有行的值都将更改。如何更改 listView 中特定行的值。请给我任何建议。
这是我的代码:
class Example extends Component {
constructor(props){
super(props);
this.state={
dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
count:1,
}
}
incrementFunc(rowID:number, listItems){
this.setState({
count : this.state.count + 1
},()=>{
this.setState({
dataSource:new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows(array)
})
})
}
decrementFunc(rowID:number,listItems){
this.setState({
count : this.state.count- 1
},()=>{
if(this.state.count <= 1){
this.setState({
count : 1
})
}
},()=>{
this.setState({
dataSource:new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows(array)
})
})
}
listOfItems(listItems, sectionID:number, rowID:number){
return(
<View style = {styles.buttonContainer}>
<View style={styles.arrowsView}>
<TouchableOpacity onPress ={this.incrementFunc.bind(this, rowID, listItems )}>
<Image style={styles.arrowStyle} source={require('@images/up-arrow.png')} />
</TouchableOpacity>
</View>
<View style={styles.numberView}>
<Text style={{fontSize:15, color:'black'}}>{this.state.count}
</Text>
</View>
<View style={styles.arrowsView}>
<TouchableOpacity onPress ={this.decrementFunc.bind(this, rowID, listItems)}>
<Image style={styles.arrowStyle} source={require('@images/down-arrow.png')} />
</TouchableOpacity>
</View>
</View>
)
}
render(){
return(
<View style={styles.listview}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.listOfItems.bind(this)}/>
</View>
);
}
}
最佳答案
count
状态变量是您用于所有行的变量,因为它是一个整数,所以它们是相同的,考虑维护一个状态变量,它是一个看起来像这样的对象 { rowId1: count1, rowId2, count2}
例如:{1: 15, 2: 10, 3: 20}
由于您的回调将 rowId
作为参数发送
<TouchableOpacity onPress ={this.incrementFunc.bind(this, rowID, listItems )}>
尝试像这样在 incrementFunc
中设置状态
incrementFunc(rowID:number, listItems){
let count = {...this.state.count}
count[rowId] = count[rowId] || 0;
count[rowId] += 1;
this.setState({ count },
()=>{
this.setState({
dataSource:new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows(array)
})
})
}
decrementFunc 可以用类似的方式修改。
然后在您的listOfItems
方法中
<Text style={{fontSize:15, color:'black'}}>
{this.state.count[rowId]}
</Text>
关于javascript - 使用react-native在listView中基于rowid增加和减少值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46784635/