问题
I managed to load custom font on my react-native expo app following the official documentation:
const App = () => {
let [fontsLoaded] = useFonts({
'Lato-Regular': require('../assets/fonts/Lato-Regular.ttf'),
'Lato-Bold': require('../assets/fonts/Lato-Bold.ttf'),
'Poppins-Light': require('../assets/fonts/Poppins-Light.ttf'),
'Poppins-Bold': require('../assets/fonts/Poppins-Bold.ttf'),
});
So I can use it with the component style:
<Text style={{
fontFamily: 'Lato-Bold'
}}>Home page.</Text>
But I would like to use it like this:
<Text style={{
fontFamily: 'Lato',
fontWeight: 'bold',
}}>Home page.</Text>
This works for system fonts, but not with custom fonts.
How can I deal with it?
回答1:
You have to use custom component and extract the font weight from it. That's how it looks like
import React from 'react';
import { View, Text as RnText, StyleSheet } from 'react-native';
const Text = ({ style, children, ...rest }) => {
let baseStyle = styles.medium;
// Multiple styles may be provided.
(Array.isArray(style) ? style : [style]).forEach((style) => {
if (style && style.fontWeight) {
baseStyle = style.fontWeight === 'bold' ? styles.bold : styles.medium;
}
});
// We need to force fontWeight to match the right font family.
return <RnText style={[baseStyle, style, { fontWeight: 'normal' }]} {...rest}>{children}</RnText>;
};
const styles = StyleSheet.create({
bold: {
fontFamily: 'Lato-Bold',
},
light: {
fontFamily: 'Lato-Light',
},
medium: {
fontFamily: 'Lato-Black',
},
});
export default Text;
来源:https://stackoverflow.com/questions/61032122/how-to-deal-with-custom-font-and-fontweight-with-react-native