我有一个表格,用户可以选择以下三个选项之一。我正确地渲染屏幕,但按钮切换不起作用。当我单击其他按钮时,tick仍然保留在第一个选项上。这是我的代码
<View style={styles.mainview}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) =>
<TouchableHighlight onPress={() => this.toggleOneYear(rowData.id, rowData.i)} style={styles.registerButton} underlayColor='#ffffff'>
<View style={styles.detailBoxTick}>
{renderIf(rowData.i == 1)(
<Image style={styles.imageTickStyle} source={this.state.payoneyear ? Images.rememberTickImg : Images.rememberUnTickImg} />
)}
{renderIf(rowData.i == 2)(
<Image style={styles.imageTickStyle} source={this.state.paytwoyear ? Images.rememberTickImg : Images.rememberUnTickImg} />
)}
{renderIf(rowData.i == 3)(
<Image style={styles.imageTickStyle} source={this.state.paythreeyear ? Images.rememberTickImg : Images.rememberUnTickImg} />
)}
<Text style={styles.tickBoxText}>
{rowData.card_duration} years Membership ${rowData.price}
</Text>
</View>
</TouchableHighlight>
}
enableEmptySections
/>
</View>
toggleOneYear(id, counter) {
if (counter == 1) {
console.log('counter ', counter)
console.log('payoneyear ', this.state.payoneyear)
this.setState(
{
payoneyear: true,
paytwoyear: false,
paythreeyear: false
}
)
console.log('payoneyear ', this.state.payoneyear)
}
else if (counter == 2) {
console.log('counter ', counter)
console.log('payoneyear ', this.state.paytwoyear)
this.setState(
{
payoneyear: false,
paytwoyear: true,
paythreeyear: false
}
)
console.log('paytwoyear ', this.state.paytwoyear)
}
else if (counter == 3) {
console.log('counter ', counter)
this.setState(
{
payoneyear: false,
paytwoyear: false,
paythreeyear: true
}
)
}
}
我在上述代码中做错了什么?有人可以帮忙吗?预先感谢
看起来您需要使用新的rowdata更新dataSource
。我猜您正在尝试使用每个TouchableHighlight Onpress来递增rowData.i
?
Renderrow的第三参数是rowID
。我们将需要此信息以知道我们需要更新哪一行。您可以将其传递给toggleOneYear
或将以下内容放入touchableHighlight OnPress:
var newArray = this.state.db.slice();
newArray[rowID] = {
// increment i, keep between 1-3
i: newArray[rowID].i + 1 > 3 ? 1 : newArray[rowID].i + 1,
};
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newArray),
db: newArray,
});
我不确定您对payxxxyear
状态变量的意图是什么,因为这些变量只有3个属性,并且您正在渲染列表数据,因此我假设您有许多将使用同一状态的touchableHighighlights。似乎应该使用数据源状态?
顺便说一句,ListView已在最新的RN版本中弃用。https://facebook.github.io/react-native/docs/listview.html#renderrow