日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2023/12/10 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [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} //將組件定義的屬性交給TextInputmultiline={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}><AutoExpandingTextInputstyle={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

總結

以上是生活随笔為你收集整理的[React Native]高度自增长的TextInput组件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。