我是原生 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/