React NativeReact-Native 开发阵营React Native开发经验集

React Native学习笔记(八)-TextInput 高度

2017-06-19  本文已影响177人  Nickyzhang

React Native TextInput 高度自适应

update

项目地址

有时我们需要根据默认的文字来显示TextInput的高度,而且可以随着文字的输入自动增加TextInput的高度。下面我们就来看一下这个是如何实现的:

TextInput属性介绍

代码伺候(去除无关代码)
/**
 * Created by Cral-Gates on 2017/5/11.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    ScrollView
} from 'react-native';
import NavigationBar from '../component/NavigationBar';
import NetUtil from '../utils/NetUtil';
import Global from '../utils/Global';

class NoteDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            noteContent: '',
            height: 50,
        }
    }

    componentDidMount() {
        this.setState({
            noteContent: this.props.noteDetail.content,
        });
    }

    render() {
        return (
            <View>
                <ScrollView>
                    <TextInput
                        style={[styles.noteDetailContent, {height: this.state.height}]}
                        multiline={true}
                        secureTextEntry={false}
                        underlineColorAndroid={'transparent'}
                        value={this.state.noteContent}
                        onChangeText={(noteContent) => this.setState({noteContent})}
                        onChange={() => this.onChange.bind(this)}
                        onContentSizeChange={(event) => this.onContentSizeChange(event)}/>
                </ScrollView>
            </View>
        )
    }
    
    onChange = (event) => {
        this.setState({
            noteContent: event.nativeEvent.text,
            height: event.nativeEvent.contentSize.height
        });
    };

    onContentSizeChange = (event) => {
        this.setState({
            height: event.nativeEvent.contentSize.height
        });
    }
}
    
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#f5f5f5'
    },
    noteDetailTitle: {
        backgroundColor: 'white',
        marginTop: 10,
        marginBottom: 2,
        marginLeft: 20,
        marginRight: 20,
        height: 35,
        fontSize: 18,
        fontWeight: '600'
    },
    noteDetailContent: {
        backgroundColor: 'white',
        marginLeft: 20,
        marginRight: 10,
        lineHeight: 20,
        fontSize: 16
    }
});

export default NoteDetail;

至此就大功告成了!有什么问题可留言交流

上一篇下一篇

猜你喜欢

热点阅读