问题描述
我正在尝试制作一个切换按钮,在点击时更改图标和图标颜色,我正在学习教程但遇到了这个问题。
我试过改变周围的东西,弄乱它,但我一直收到同样的错误: “找不到变量:setState”
导致问题的代码:
import { View,Text,StyleSheet,Image,TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { Caption } from "react-native-paper"
const FlagSection = (props) => {
const state = {
heartIcon: "ios-heart-outline",liked: false
}
const toggleLike = () => {
setState({
liked: !state.liked
})
if(state.heartIcon){
setState({
heartIcon: "ios-heart"
})
}else{
setState({
heartIcon: "ios-heart-outline"
})
}
}
return (
<View style={ styles.container }>
<View style={ {flex:1} }>
<View style= {styles.flagInfo}>
<View style= {styles.imageContent}>
<Image
source={ props.detail.flag }
size={60}
/>
<View style= {styles.currencyContent}>
<Text> {props.detail.abbreviation} </Text>
<Caption style={ styles.caption }> {props.detail.name} </Caption>
</View>
<View style= {styles.likeButton}>
<TouchableOpacity onPress={ toggleLike }>
<Icon name={state.heartIcon} size={40} style={{color: state.heartIcon === "ios-heart-outline" ? "black" : "red"}}/>
</TouchableOpacity>
</View>
</View>
</View>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,},flagInfo: {
paddingLeft: 20,borderWidth: 5,imageContent: {
flexDirection: "row",marginTop: "3%",currencyContent: {
marginLeft: "3%",flexDirection: "column"
},caption: {
fontSize: 16,paddingTop: "3%",lineHeight: 14,likeButton: {
flexDirection: "row",justifyContent: "flex-end",marginLeft: "auto"
}
});
export default FlagSection;```
解决方法
您需要在功能组件中使用 useState
定义初始状态:
const [state,setState] = useState({
heartIcon: "ios-heart-outline",liked: false
});
然后,为了在不丢失另一个属性的情况下更新单个属性,请传播现有状态:
setState({
...state,liked: !state.liked
})
但我强烈建议将属性分离到不同的有状态变量中:
const [heartIcon,setHeartIcon] = useState('ios-heart-outline');
const [liked,setLiked] = useState(false);
然后您只需要使用,例如,setLiked(!liked)
而不必还管理相同状态变量中先前值的复制。