简体   繁体   English

渲染多个<Switch>内部地图反应原生

[英]render multiple <Switch> inside map react native

I'm having trouble rendering multiple switches inside map.我在地图内渲染多个开关时遇到问题。

I'm having an array looking like this:我有一个看起来像这样的数组:

array: [
   {
      "title": "test1"
   },
   {
      "title": "test2"
   }
]

Then in the render and return i'm using map and want to display 2 switches:然后在渲染和返回中我正在使用地图并希望显示 2 个开关:

{this.state.array.map((item, index) => (
   <View key={index}>
     <Switch
       trackColor={{ false: "#767577", true: "#81b0ff" }}
       thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
       ios_backgroundColor="#3e3e3e"
       onValueChange={toggleSwitch}
       value={isEnabled}
      />             
    </View>
))}

The "isEnable" have to be uniq for every switch and I don't know the best practise for doing this?每个开关的“isEnable”必须是 uniq,我不知道这样做的最佳实践?

array: [
   {
      "title": "test1",
      isEnabled:false,
   },
   {
      "title": "test2"
      isEnabled:true,
   }
]


{this.state.array.map((item, index) => (
   <View key={index}>
     <Switch
       trackColor={{ false: "#767577", true: "#81b0ff" }}
       thumbColor={item.isEnabled ? "#f5dd4b" : "#f4f3f4"}
       ios_backgroundColor="#3e3e3e"
       onValueChange={toggleSwitch}
       value={item.isEnabled}
      />             
    </View>
))}

the best approache is to include if the switch is enabled or not in your array最好的方法是在您的阵列中包含是否启用了开关

const myArray = [{"title": "test1",isEnabled:true},{"title": "test2",isEnabled:false}]
{myArray.map((item, index) => ( 
<View key={index}> 
 <Switch trackColor={{ false: "#767577", true: "#81b0ff" }}
   thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
   ios_backgroundColor="#3e3e3e"
   onValueChange={toggleSwitch}
   value={item.enabled}
  />             
</View>))}

and in your toggles Switch function make sure to update your array并在您的切换开关功能中确保更新您的阵列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM