1. 程式人生 > >[React Native]高度自增長的TextInput元件

[React Native]高度自增長的TextInput元件

在開發中,我們有時候有這樣的需求, 希望輸入區域的高度隨著輸入內容的長度而增長, 如下:
這裡寫圖片描述
這時候我們需要自定義一個元件:
在專案中建立AutoExpandingTextInput.js

import React, {Component} from 'react';
import {AppRegistry, TextInput, StyleSheet} from 'react-native';

export default class AutoExpandingTextInput extends Component {
    // 構造
    constructor(props) {
        super
(props); // 初始狀態 this.state = { text: '', height: 0 }; this.onChange = this.onChange.bind(this); } onChange(event) { console.log(event.nativeEvent); this.setState({ text: event.nativeEvent.text, height:event.nativeEvent.contentSize.height }); } onContentSizeChange(params){ console.log(params); } render() { return
( <TextInput {...this.props} //將元件定義的屬性交給TextInput multiline={true} onChange={this.onChange} onContentSizeChange={this.onContentSizeChange} style={[styles.textInputStyle,{height:Math.max(35,this.state.height)}]} value={this
.state.text} /> ); } } const styles = StyleSheet.create({ textInputStyle: { //文字輸入元件樣式 width: 300, height: 30, fontSize: 20, paddingTop: 0, paddingBottom: 0, backgroundColor: "grey" } });

在多行輸入(multiline={true})的時候,可以通過onChange回撥函式,獲取內容的高度event.nativeEvent.contentSize.height,然後修改內容的高度。

接下來修改index.ios.js或者index.android.js 如下:

import AutoExpandingTextInput from './AutoExpandingTextInput';

class AwesomeProject extends Component {
    _onChangeText(newText) {
        console.log('inputed text:' + newText);
    }

    render() {
        return (
            <View style={styles.container}>
                <AutoExpandingTextInput
                    style={styles.textInputStyle}
                    onChangeText={this._onChangeText}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
        borderWidth: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    textInputStyle: { //文字輸入元件樣式
        width: 300,
        height: 50,
        fontSize: 20,
        paddingTop: 0,
        paddingBottom: 0,
        backgroundColor: "grey"
    }
});

當然我們知道在IOS端TextInput/Text元件預設不會水平居中的,需要在外層額外巢狀一層View,可以參考從零學React Native之10Text
執行結果:

這裡寫圖片描述

更多精彩請關注微信公眾賬號likeDev
這裡寫圖片描述