我尝试在我的无状态组件内部使用一个函数。但是它不能正常工作。
const selectedColor = function ({color}) {
switch (color) {
case 'green':
return styles.green;
break;
case 'blue':
return styles.blue;
break;
case 'red':
return styles.red;
break;
default:
Alert.alert("Undefined Color!");
}
}
const LightBulb = ({isLit, lightColor}) => {
return (
<View
style={[isLit ? selectedColor(lightColor) : styles.green, {alignSelf: 'stretch'}]}>
<Text>{isLit ? 'ON' : 'OFF'}</Text>
</View>
);
}
isLit
为真时,应触发selectedColor(lightColor)
。一旦被触发,即使lightColor
是贪婪,红色或蓝色之一,它也会进入Alert
。您能解释为什么会这样吗?有人可以给我正确的方法吗?
我已经对您的代码进行了一些更改,现在可以正常运行,演示在这里。
https://snack.expo.io/@waheed25/smiling-carrot
或者这是正在运行的代码,您只需要在函数中传递颜色,它就会显示出来。
import { View, Text } from 'react-native'
import React, {useState} from 'react'
const App =()=>{
const [isLit, setIsLit] = useState(true)
const selectedColor = (color)=> {
console.log('color:', color)
switch (color) {
case 'green':
return {backgroundColor: 'green'};
case 'blue':
return {backgroundColor: 'blue'};
case 'red':
return {backgroundColor: 'red'};
default:
Alert.alert("Undefined Color!");
}
}
return (
<View
style={[isLit ? selectedColor('red') : {backgroundColor: 'green'}, {alignSelf: 'stretch', height: 200}]}>
<Text>{isLit ? 'ON' : 'OFF'}</Text>
</View>
);
}
export default App;
当我删除{color}的{}时,它起作用。