首页 > 解决方案 > Auto shrink text - React Native

问题描述

I'm new to React native. As you can see in the photo, there is 1 text input and 1 box showing the typed text. My font size is 14. I want my font size to be reduced when the text I write to the input takes up too much space on the board. So I don't want any text left out of the box. I want the text to shrink automatically when the text is ready to go out of the box. How can i do that?

enter image description here

My codes:

import React, { useState } from 'react'
import { Text, View, TextInput, StyleSheet } from 'react-native'



const Test = () => {

    const [text, setText] = useState('')

    return (
        <View style={styles.container}>
            <View style={styles.board}>
                <Text style={styles.text}>
                    {text}
                </Text>
            </View>
            <View style={styles.input}>
                <TextInput
                    onChangeText={setText}
                />
            </View>
        </View>
    )
}

export default Test

const styles = StyleSheet.create({
    container:{ 
        backgroundColor: 'purple', 
        flex: 1, 
        justifyContent: 'center', 
        alignItems: 'center' 
    },
    board:{
        height: 50, 
        width: 100, 
        backgroundColor: 'grey', 
        marginBottom: 20
    },
    input:{
        height: 50, 
        width: 100, 
        backgroundColor: 'white' 
    },
    text:{
        fontSize:14
    }
})

标签: javascriptreact-native

解决方案


你可以使用这种方法 - https://snack.expo.dev/IFjJfnj6y,为了获取当前文本的大小,你也可以使用这个链接 - React-native view auto width by text inside


推荐阅读