Как применить собственный шрифт expoact-native для всего контейнера - PullRequest
0 голосов
/ 17 октября 2019

Я попытался загрузить собственный шрифт для моего приложения-приложения, которое я разрабатываю с помощью expo, но я не знаю, как проще загрузить шрифт для всего контейнера экрана.

В настоящее время я использовал официальную выставочную документацию: Документация по пользовательским шрифтам Expo

Они сказали, что используют функцию Font.loadAsync (), а затем используют this.state.fontLoaded?, например:

    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
  {
    this.state.fontLoaded ? (
      <Text style={{ fontFamily: 'open-sans-bold', fontSize: 56 }}>
        Hello, world!
      </Text>
    ) : null
  }
</View>

но существовало ли, например, решение для применения шрифта к контейнеру? Я думаю, что нелегко принудительно окружать КАЖДЫЙ текстовый элемент одной и той же функцией ...

В настоящее время шрифт загружается в ОДНОМ текстовом элементе, но я хотел бы иметь возможность легко использовать мой шрифт вконтейнер, или много текстовых элементов одновременно.

Вот мой код:

    state = {
        fontLoaded: false,
    };

    async componentDidMount() {
        await Font.loadAsync({
            'ubuntu-medium': require('../assets/fonts/Ubuntu-Medium.ttf'),
        });
        this.setState({ fontLoaded: true });
    }
    render() {
        return (
            <View style={styles.main_container}>

                <View style={styles.inner_main_container}>

                    <View style={styles.top_links_container}>
                        <View style={styles.profile_and_arrow_container}>
                            <Icon
                                name='arrow-back'
                                color='white'
                                style={styles.icon} />
                            {
                                this.state.fontLoaded ? (
                                    <Text style={styles.top_links_profile}>Profil</Text>
                                ) : null
                            }
                        </View>
                        <View style={styles.profile_edit_container}>
                            <Text style={styles.top_links_edit}>Editer</Text>
                        </View>
                    </View>
                    <View style={styles.profile_avatar_container}>
                        <Avatar
                            rounded
                            size='xlarge'
                            source={{ uri: 'https://randomuser.me/api/portraits/men/27.jpg' }}>
                        </Avatar>
                    </View>
                    <View style={styles.profile_infos_container}>
                        {
                            this.state.fontLoaded ? (
                                <Text style={styles.user_name}> Dupont Jean </Text>
                            ) : null
                        }
                        <Text style={styles.user_title}> CSD - Product Owner </Text>
                    </View>
                    <View style={styles.subprofile_infos_container}>

                        <View style={styles.user_experience}>
                            <Text>Experience </Text>
                            <Text style={styles.user_experience_years}> 7ans</Text>
                        </View>

                        <View style={styles.user_grade}>
                            <Text>Grade </Text>
                            <Text style={styles.user_grade_letter}> D </Text>
                        </View>
                    </View>
                    <View numberOfLines={6}>
                        <Text style={styles.user_bio}> Lorem Ipsum is simply dummy text of the printing and
                                    typesetting industry. Lorem Ipsum has been the industry's standard…</Text>
                    </View>
                    <View>
                        <Text style={styles.user_bio_see_more_link}> Voir plus</Text>
                    </View>
                    <Divider style={styles.divider} />
                    <View style={styles.bottom_container}>
                        <View style={styles.bottom_cm_text_info_container}>
                            <Text style={styles.bottom_cm_text_info}>Carrière Manager d'Evelyne</Text>
                            <Text style={styles.bottom_cm_text_user_name}>Jerôme Durand</Text>
                        </View>
                        <View style={styles.bottom_cm_avatar}>
                            <Avatar
                                rounded
                                size='small'
                                source={{ uri: 'https://randomuser.me/api/portraits/men/27.jpg' }}
                            />
                            <Icon
                                name='right'
                                type='antdesign'
                                color='grey'
                                onPress={() => console.log('hello button cm view')}
                            />
                        </View>
                    </View>
                </View>
            </View>
        );
    }
}

1 Ответ

0 голосов
/ 28 октября 2019

Наконец-то я нашел хорошо работающее решение.

Мне пришлось создать такой компонент, как этот:

1. Например, создайте пользовательский компонент TextCustom.js и поместите его в:

import React from 'react'
import { Text, StyleSheet, View, ActivityIndicator } from 'react-native'
import * as Font from 'expo-font'

export default class TextCustom extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            loading: true,
        }
    }

    async componentWillMount() {
        await Font.loadAsync({
            'Ubuntu': require('./../assets/fonts/Ubuntu-Medium.ttf')
        })
        this.setState({ loading: false })
    }

    render() {
        if (this.state.loading) {
            return <ActivityIndicator/>
        }
            return (
                <View>
                    <Text style={[styles.defaultStyle, this.props.style]}>
                        {this.props.children}
                    </Text>
                </View>
            )
    }
}

const styles = StyleSheet.create({
    defaultStyle: {
        fontFamily: 'Ubuntu'
    },
})

Не забудьте импортировать шрифт из Expo (для людей, использующих Expo)

2. в компоненте, который вы хотите использовать пользовательский шрифт, просто импортируйте и используйте только что созданный компонент:

import TextCustom from './TextCustom'
import TextBoldCustom from './TextBoldCustom'  (if you want to use a Bold or italic font)

и используйте его:

<View>
    <TextCustom style={styles.info_welcome}>Bonjour</TextCustom>
</View>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...