如何更改从数组动态创建的TouchableOpacity的backgroundColor?

时间:2020-01-02 11:38:47

标签: react-native touchableopacity

我想更改TouchableOpacity的backgroundColor和BorderColor。我知道我可以使用状态来更改TouchableOpacity BGColor onPress,但是TouchableOpacitys是从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>
);

此代码已经可以显示创建的按钮,我只需要按一下即可更改颜色。

2 个答案:

答案 0 :(得分:2)

state对象可以具有一个名为touchableOpacityIndexPressed的属性,该属性在开始时以-1进行初始化。

constructor(props) {
  super(props);
  this.state = { touchableOpacityIndexPressed: -1 }
  ...
}

将可触摸对象推入数组时,可以执行以下操作:

<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)

答案 1 :(得分:1)

我将为TouchablOpacity创建一个单独的类组件,并在那里实现onPress逻辑,然后在您的数组中使用新创建的组件,如下所示:

 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(
          <NewComponent textToDispaly = {sizeTitle}/>
     )
     }
   }
 }