首页 > 解决方案 > how to do conditional rendering and non-conditional rendering of both components in Map function react -native

问题描述

i want to display ItemName and if ItemDeliveryStatus==1 then show disabled TextInput else display editable TextInput inside Map function react-native

const [arrayList, setArraylist] = useState([
        { id: 0,  ItemName: 'A',   ItemDeliveryStatus:1 },
        { id: 1, , ItemName: 'B', ItemDeliveryStatus:1 },
        { id: 2,  ItemName: 'C', ItemDeliveryStatus:1  },
        { id: 3,  ItemName: 'D', ItemDeliveryStatus:1  },
      ]);


{
   arrayList.map((items,index)=>{
     return <View>
              <Text >{items.ItemName}</Text>

          if(items.ItemDeliveryStatus== 1){
            return <View> 
                      <TextInput   editable={false} /> 
                   </View>
           }else
           {
                <View> 
                  <TextInput   editable={true} /> 
                </View>
            }

     </View>

标签: react-native

解决方案


您可以使用花括号在 JSX 组件中嵌入表达式,并使用三元运算符作为条件,因此以下内容应该有效:

{ items.ItemDeliveryStatus == 1 ?
  (<View> 
     <TextInput   editable={false} /> 
   </View>) : 
  (<View> 
     <TextInput   editable={true} /> 
   </View>)
}

它将在组件的返回内部工作。
例如:

...
return (
  <View>
    { 
      items.ItemDeliveryStatus == 1 ?
      (<View> 
         <TextInput   editable={false} /> 
       </View>) : 
      (<View> 
         <TextInput   editable={true} /> 
       </View>)
    }
  </View>
)

在这里,给你做了个小零食,代码完整。


推荐阅读