[React Native]高度自增长的TextInput组件
来源:互联网 发布:java和php的全面对比 编辑:程序博客网 时间:2024/05/28 11:29
之前我们学习了从零学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
0 0
- [React Native]高度自增长的TextInput组件
- React Native高度自增长的TextInput组件
- React-Native之TextInput实现高度自增长解决方案
- react-native-auto-expanding-textinput 根据输入的内容自增长高度
- React-Native TextInput组件的主要属性
- react native 的TextInput组件问题
- React Native 组件之TextInput
- react native textInput随内容高度设置textinput高度
- React Native的TextInput组件去掉下划线和使用背景图片
- React Native 组件 --TextInput处理文本输入
- React Native学习笔记(3)--TextInput组件
- React Native-8.React Native TextInput组件详解
- React Native组件篇(三) — TextInput组件
- React Native组件(四)TextInput组件解析
- react native TextInput 走过的坑...
- (三)React Native---TextInput
- React-native TextInput初识
- react native ,隐藏TextInput
- [299] Bulls and Cows
- 数据工程师必知算法:蓄水池抽样
- 如何知道linux内核是否开启CONFIG_PACKET选项
- 虚拟机刚装了linux 系统,如何添加一块新硬盘?
- 笔记---第一章
- [React Native]高度自增长的TextInput组件
- leetcode:Trie:Implement Trie (Prefix Tree)(208)
- HDU2044一只小蜜蜂...
- 文件存储密码
- ajax请求中传输文乱码的问题
- R的入门学习
- call()的用法
- Maven - 创建工程
- 如何理解面向对象(POO)?