【问题标题】:How to change backgroundColor of a TouchableOpacity created dynamically from array?如何更改从数组动态创建的 TouchableOpacity 的背景颜色?
【发布时间】:2020-01-02 11:38:47
【问题描述】:

我想更改 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>
);

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

【问题讨论】:

    标签: react-native touchableopacity


    【解决方案1】:

    state 对象可以有一个名为touchableOpacityIndexPressed 的属性,该属性以-1 开头。

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

    当touchable被push到数组中时,可以进行如下操作:

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

    【讨论】:

      【解决方案2】:

      我会为 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}/>
           )
           }
         }
       }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-30
        • 2014-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多