在无状态组件中传递函数不起作用
Passing function inside a stateless component is not working
我尝试在我的无状态组件中使用一个函数。但它不能正常工作。
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
是greed,red,blue其中之一,也会去Alert
。你能解释为什么会这样吗?有人能给我一个正确的方法吗?
我对你的代码做了一些修改,现在可以使用了,Demo 在这里。
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;
当我删除 {} of {color} 时,它起作用了。
我尝试在我的无状态组件中使用一个函数。但它不能正常工作。
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
是greed,red,blue其中之一,也会去Alert
。你能解释为什么会这样吗?有人能给我一个正确的方法吗?
我对你的代码做了一些修改,现在可以使用了,Demo 在这里。
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;
当我删除 {} of {color} 时,它起作用了。