我想更改 TouchableOpacity 的 backgroundColor 和 BorderColor。我知道我可以使用 state 来更改 TouchableOpacity BGColor onPress,但是 TouchableOpacity 是从 arrayList 动态创建的,我只想更改按下的 touchableOpacity 的 backgroundColor 和 BorderCorlor。
这是我创建按钮的代码:
var sizeOptions = [];
for (var i = 0; i < product.Items[0].Items.length; i++) {
for (var j = 0; j < product.Items[0].Items[i].SKUOptions.length; j++) {
if (product.Items[0].Items[i].SKUOptions[j].Alias == 'Tamanho') {
var sizeTitle = product.Items[0].Items[i].SKUOptions[j].Title;
sizeOptions.push(
<TouchableOpacity style={{marginLeft:20, height:40, width:40, borderRadius:1, borderWidth:1, borderStyle: 'solid', borderColor:'#000', backgroundColor:'#fff'}} key = {i} onPress={() => this.selectSize(sizeTitle)}>
<Text style={[{marginTop:10, width:40, height:40, textAlign: 'center'}]}> {sizeTitle} </Text>
</TouchableOpacity>
)
}
}
}
return (
<ScrollView contentContainerStyle={{flexGrow: 1, justifyContent: 'center'}} horizontal={true} style={{marginTop:15, marginLeft: 15}}>
{ sizeOptions }
</ScrollView>
);
此代码已经可以显示创建的按钮,我只需要在按下时更改颜色。
该state
对象可以有一个叫做财产touchableOpacityIndexPressed
这与初始化的-1
开头。
constructor(props) {
super(props);
this.state = { touchableOpacityIndexPressed: -1 }
...
}
当touchable被推到数组时,你可以做到以下几点:
<TouchableOpacity style={{marginLeft:20, height:40, width:40, borderRadius:1, borderWidth:1, borderStyle: 'solid', borderColor: this.state.touchableOpacityIndexPressed === (i + j) ? 'red' : '#000', backgroundColor: this.state.touchableOpacityIndexPressed === (i + j) ? 'blue' :'#fff'}} key = {i} onPress={() => this.selectSize(sizeTitle, (i + j)}>
确保在selectSize
方法的touchableOpacityIndexPressed
属性中设置正确的状态,在我的示例中,我将其设置为(i + j)
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句