[React Native]高度自增长的TextInput组件

之前我们学习了从零学React Native之11 TextInput了解了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,公众账号名称:爱上Android。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值