改变函数中变量的状态
2022-06-08
235
我有两种字体,一种是应用使用阿拉伯语时使用的字体,另一种是应用使用英语时使用的字体。我的想法是在顶部声明状态,但当用户更改字体时,它会恢复为 false 状态。
const App = ({navigation}) => {
const [newFont, setNewFont] = useState();
i18n.on('languageChanged', () => {
console.log('languageChanged');
setNewFont(true);
});
const customTextProps = {
style: {
fontFamily: Fonts.GLOBAL_APP_FONT,
},
};
const customTextInputProps = {
style: {
fontFamily: Fonts.GLOBAL_APP_FONT,
},
};
setCustomText(customTextProps);
setCustomTextInput(customTextInputProps);
const arabictextProps = {
style: {
fontFamily: Fonts.GLOBAL_APP_ARABIC_FONT,
},
};
if (newFont === true) {
setCustomText(arabictextProps);
setCustomTextInput(arabictextProps);
console.log('fontChange', newFont);
} else {
console.log('fontChange', newFont);
setCustomText(customTextProps);
setCustomTextInput(customTextProps);
}
当用户触发 i18 .on 函数时,状态被声明为 true,但应用会刷新并再次更改状态。
请帮我想办法更改状态...
2个回答
您不应该在函数内部更改状态,因为这会导致循环:每次更新状态时,都会回调该函数。
尝试以下示例,其中只有在调用 languageChanged 时状态才会改变:
const customTextProps = {
style: {
fontFamily: Fonts.GLOBAL_APP_FONT
}
}
const customTextInputProps = {
style: {
fontFamily: Fonts.GLOBAL_APP_FONT
}
}
const arabictextProps = {
style: {
fontFamily: Fonts.GLOBAL_APP_ARABIC_FONT
}
}
const App = ({ navigation }) => {
const [customText, setCustomText] = useState(customTextProps)
const [customTextInput, setCustomTextInput] = useState(customTextInputProps)
useEffect(() => {
i18n.on('languageChanged', () => {
console.log('languageChanged')
setCustomText(arabictextProps)
setCustomTextInput(arabictextProps)
})
}, [])
}
Nico Montanari
2022-06-08
const customTextProps = {
style: {
fontFamily: Fonts.GLOBAL_APP_FONT,
},
};
const customTextInputProps = {
style: {
fontFamily: Fonts.GLOBAL_APP_FONT,
},
};
setCustomText(customTextProps);
setCustomTextInput(customTextInputProps);
const arabictextProps = {
style: {
fontFamily: Fonts.GLOBAL_APP_ARABIC_FONT,
},
};
if (i18n.language === 'ar') {
setCustomText(arabictextProps);
setCustomTextInput(arabictextProps);
} else {
setCustomText(customTextProps);
setCustomTextInput(customTextProps);
}
我需要做的就是更改 if 语句来检查应用程序是否是阿拉伯语。
JasonBeedle
2022-06-08