react-native - react native View 条件渲染

标签 react-native

我是原生 react 新手。 所以我有这个组件:它将从父组件获取 prop x 。 是否可以根据 x 更改仅 Yollow View 的背景颜色? 或者我应该单独渲染 View 而不是使用 map ? 任何帮助将不胜感激

     const [colors, setColors] = useState(["yellow", "blue", "green", "red"]);
     return ( <View style={{
        width: "100%",
        height: "100%",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        flexWrap: "wrap",}}>
      {colors.map((color, index) => (
        <View
          key={index}
          style={{height: "25%",backgroundColor:color,}}></View>))}
         </View>);};```

最佳答案

backgroundColor: color === 'yellow' ? (xCondition ? randomColor : color) : color

不建议嵌套三元运算,因此更好的方法是使用一个返回颜色的函数,例如:

function getColor(x, currentColor){
  if(currentColor === 'yellow') {
    return xCondition ? randomColor : currentColor
  }
  return currentColor
}

backgroundColor: getColor(x, currentColor)

关于react-native - react native View 条件渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69889218/

相关文章:

typescript - 用 RN Detox 模拟

reactjs - 从 useEffect() Hook 调用时,layoutAnimation 不起作用

javascript - 在 Javascript 中使用 map 数组时未定义的值

javascript - 这个 setState 的 React hooks 等价物是什么?

react-native - 我们如何将 iOS 和 Android 项目隔离到他们自己的仓库中,但维护一个 React-native 仓库?

android - react native WebView 与 Cordova

react-native - 如何知道 FlatList 中滚动(向上或向下)的状态?

javascript - React Native - 如何从 ScrollView 获取 View 的 Y 偏移值?

react-native - RNFirebaseAdMobPackage 在 native 版本 0.60.4 中引发错误

javascript - React Native 信用卡扫描仪面临问题