之前我們學習了從零學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